package learn.navdrawbase;

import android.app.TaskStackBuilder;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
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 Activity3 extends BaseActivity {

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;
    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_3);

        Log.v("info", "URL called");
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = "http://omany.fr/SQL/lieux.php"; // https://lecarpentier.users.greyc.fr/restapi/messages.php
        Log.v("truc", url);

        // 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
        int srcImage = R.drawable.image1;
        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);

        //remplir les tableaux pour l'instant avec des valeurs a la con pour etat et image
        for (int i = 0; i < lieux.size() ; i++) {
            etat.add("Non occupé");
            images.add(srcImage);
        }


        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);
        }

        // Keys used in Hashmap
        String[] from = {"image", "lieu", "etat"};

        // Ids of views in listview_layout
        int[] to = {R.id.image0, R.id.lieu0, R.id.etat0};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.content_3, from, to);

        // Getting a reference to listview of main.xml layout file
        ListView listView = (ListView) findViewById(R.id.listview);

        // Setting the adapter to the listView
        listView.setAdapter(adapter);


        //Set nav drawer selected to second item in list
        mNavigationView.getMenu().getItem(2).setChecked(true);

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
       // client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

        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 void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Activity3 Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://learn.navdrawbase/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }
*/

/*
    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Activity3 Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://learn.navdrawbase/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }

*/
}
