package com.example.patrice.listview_all_db_records;

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

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

//https://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

// https://github.com/Oclemy/MySQL_ListView_Images



/***************************************************************************/

//http://www.simplylearnprogramming.com/display-image-android-listview/6  ++++++ code original :)

// http://wptrafficanalyzer.in/blog/android-lazy-loading-images-and-text-in-listview-from-http-json-data/

// https://androidjson.com/android-json-parsing-recyclerview-image-text/

//https://www.simplifiedcoding.net/android-upload-image-using-php-mysql-android-studio/

// http://www.androidbegin.com/tutorial/android-json-parse-images-and-texts-tutorial/

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

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

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity
{
    ListView listView;
    //private static final String newurl = "http://localhost IP or domain name here/RegistrationLogin/getandroidosnames.php";
    private static final String newurl = "http://analog-design.net/WORKAREA/WEBSITE/reservation/read_all_records.php";

    private String json;
    private JSONArray urls;
    public  Getjson getjsonobj;
    Customadapter customadapter;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.lst);
        getURLs();
    }

    private void getImages()
    {

        class GetImages extends AsyncTask<Void, Void, Void>
        {
            ProgressDialog loading;

            @Override
            protected void onPreExecute()
            {
                super.onPreExecute();
                loading = ProgressDialog.show(MainActivity.this, "Loading Menu", "Please wait...", false, false);
            }

            @Override
            protected void onPostExecute(Void v)
            {
                super.onPostExecute(v);
                loading.dismiss();

                customadapter = new Customadapter(MainActivity.this, getjsonobj.Android_Name ,getjsonobj.bitmaps );
                listView.setAdapter(customadapter);
            }

            @Override
            protected Void doInBackground(Void... voids)
            {
                try
                {
                    getjsonobj.getAllImages();
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }

                return null;
            }
        }

        GetImages getImages = new GetImages();
        getImages.execute();
    }


    private void getURLs()
    {

        class GetURLs extends AsyncTask<String, Void, String>
        {
            ProgressDialog loading;

            @Override
            protected void onPreExecute()
            {
                super.onPreExecute();
                loading = ProgressDialog.show(MainActivity.this, "Loading...", "Please Wait...", true, true);
            }

            @Override
            protected void onPostExecute(String s)
            {
                super.onPostExecute(s);
                loading.dismiss();
                getjsonobj = new Getjson(s);
                getImages();
            }

            @Override
            protected String doInBackground(String... strings)
            {
                BufferedReader bufferedReader = null;

                try
                {
                    URL url = new URL(strings[0]);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();

                    bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    String json;
                    while ((json = bufferedReader.readLine()) != null)
                    {
                        sb.append(json + "\n");
                    }

                    return sb.toString().trim();
                }

                catch (Exception e)
                {
                    return null;
                }
            }
        }

        GetURLs gu = new GetURLs();
        gu.execute(newurl);

    }
}


/***************************************************************************/


/*
public class MainActivity extends ListActivity
{

    final String src[] = {};


    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    //private static String url_all_products = "https://api.androidhive.info/android_connect/get_all_products.php";
    private static String url_all_products = "http://analog-design.net/WORKAREA/WEBSITE/reservation/read_all_records.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_ID = "id";
    private static final String TAG_IMAGE = "image";
    private static final String TAG_NOM = "nom";

    // products JSONArray
    JSONArray products = null;

    List<String> planets = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_products);

       // ArrayList<String> srcList = new ArrayList<String>(Arrays.asList(src));

       // srcList.add("toto");;

        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllProducts().execute();

        // Get listview
        ListView lv = getListView();

        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {


            }
        });

    }


    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
/*
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
/*
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
/*
        protected String doInBackground(String... args)
        {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try
            {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++)
                    {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        //String id = c.getString(TAG_ID);
                        String nom = c.getString(TAG_NOM);
                        String url_image = c.getString(TAG_IMAGE);


                        planets.add(url_image);;


                        //src[i] = url_image;




                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        //map.put(TAG_ID, id);
                        map.put(TAG_NOM, nom);
                        map.put(TAG_IMAGE, url_image);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                }

                else
                {
                    // no products found
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
/*
        protected void onPostExecute(String file_url)
        {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread

            runOnUiThread(new Runnable()
            {
                public void run()
                {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
/*
                    ListAdapter adapter = new SimpleAdapter(
                            MainActivity.this, productsList,
                            R.layout.list_item, new String[] { TAG_IMAGE, TAG_NOM}, new int[] { R.id.image, R.id.nom });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
}
*/