package learn.navdrawbase;

import android.app.TaskStackBuilder;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import com.google.android.gms.common.api.GoogleApiClient;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class Activity_List extends BaseActivity {

    private ArrayList<String> lieux = new ArrayList<String>();

    private class MyJsonReponse implements Response.Listener<JSONArray> {
        @Override
        public void onResponse(JSONArray response) throws JSONException {
            Log.v("info", response.toString());

            for (int i=0; i<response.length(); i++) {
                try {
                    JSONObject jo = response.getJSONObject(i);
                    lieux.add(jo.getString("NomLieu"));

                } catch (Exception e) {
                    Log.v("debug", e.toString());
                }
            }
            afficherLieux();
            mNavigationView.getMenu().getItem(1).setChecked(true);
        }
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = "http://omany.fr/SQL/lieux.php";

        // Request a string response from the provided URL.
        JsonArrayRequest jsonRequest = new JsonArrayRequest(url,
                new MyJsonReponse(), // la classe interne qui sera appelée quand on reçoit la réponse
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.v("info", "That didn't work!");
                    }

                }
        );
        // Add the request to the RequestQueue.
        queue.add(jsonRequest);

        Log.v("truc", "ok");

    }


    protected void afficherLieux() {

        // Each row in the list stores country name, currency and flag
        List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
        ArrayList<String> etat = new ArrayList<String>(); //fréquentation du lieu
        ArrayList<Integer> images = new ArrayList<Integer>(); //image du lieu
        ArrayList<Integer> srcImages = new ArrayList<Integer>();
        srcImages.add(R.drawable.carrefour);srcImages.add(R.drawable.auchan);
        srcImages.add(R.drawable.superu);srcImages.add(R.drawable.cora);srcImages.add(R.drawable.laposte);

        for (int i = 0; i < lieux.size() ; i++) {
            etat.add("Non occupé");
            images.add(srcImages.get(i%srcImages.size()));
        }


        for (int i = 0; i < lieux.size(); i++) {
            HashMap<String, String> hm = new HashMap<String, String>();
            hm.put("lieu", "Lieu : " + lieux.get(i));
            hm.put("etat", "Etat : " + etat.get(i));
            hm.put("image", images.get(i).toString());
            aList.add(hm);
        }

        // Clés de la hashmap
        String[] from = {"image", "lieu", "etat"};

        // Id des items de listView
        int[] to = {R.id.image0, R.id.lieu0, R.id.etat0};

        // Instanciation d'un adapateur pour stocker les items
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.content_list, from, to);

        // Reference du listView
        ListView listView = (ListView) findViewById(R.id.listview);

        // Mettre l'adaptater à la listeView
        listView.setAdapter(adapter);


        //Le deuxième item de la liste est séléctionné
        mNavigationView.getMenu().getItem(2).setChecked(true);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                onItemClique(parent, view, position, id);
            }});

    }

    protected void onItemClique(AdapterView<?> parent, View view, int position, long id){
        Intent myIntent = new Intent(this, Activity_Place.class);
        myIntent.putExtra("id", id);
        myIntent.putExtra("position", position);
        createBackStack(myIntent);
    }


    private void createBackStack(Intent intent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            TaskStackBuilder builder = TaskStackBuilder.create(this);
            builder.addNextIntentWithParentStack(intent);
            builder.startActivities();
        } else {
            startActivity(intent);
            finish();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_activity3, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_search) {
            createBackStack(new Intent(this, Activity_Search.class));
        }

        return super.onOptionsItemSelected(item);
    }
}
