package com.example.patrice.json_return;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.widget.BaseAdapter;


//https://www.learn2crack.com/2013/10/android-asynctask-json-parsing-example.html

public class MainActivity extends AppCompatActivity
{

    //JSON Node
    private static final String TAG_USER = "user";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";

    JSONArray element = null;

    private String pipo = "";

    private static final String TAG = "ERROR";
    private static final int IO_BUFFER_SIZE = 4 * 1024;

    ListView lstView1;

    ArrayList<HashMap<String, String>> AppArrList = new ArrayList<HashMap<String, String>>();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        lstView1 = (ListView)findViewById(R.id.listView1);

        // Permission StrictMode

        if (android.os.Build.VERSION.SDK_INT > 9)
        {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        String pipo = null;

        try
        {
            pipo = new JSONParse().execute().get();
        }

        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

        catch (ExecutionException e)
        {
            e.printStackTrace();
        }

        int l = pipo.length();
        String toto = "5524564";
        int v = 4;
        v = v + 7;
        // String aaa = "{"result":[{"ImageID":"1","ImageDesc":"My Sea View 1","ImagePath":"http:\/\/analog-design.net\/WORKAREA\/WEBSITE\/reservation\/luba_74800_1.jpg"},{"ImageID":"2","ImageDesc":"My Sea View 2","ImagePath":"http:\/\/analog-design.net\/WORKAREA\/WEBSITE\/reservation\/luba_74800_2.jpg"},{"ImageID":"3","ImageDesc":"My Sea View 3","ImagePath":"http:\/\/analog-design.net\/WORKAREA\/WEBSITE\/reservation\/luba_74800_3.jpg"},{"ImageID":"4","ImageDesc":"My Sea View 4","ImagePath":"http:\/\/analog-design.net\/WORKAREA\/WEBSITE\/reservation\/luba_74800_12.jpg"}]}n";

        try
        {
            JSONObject jObj = null;
            jObj = new JSONObject(pipo);
            element = jObj.getJSONArray("result");

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

            for (int i = 0; i < element.length(); i++) {
                JSONObject x = element.getJSONObject(i);
                map = new HashMap<String, String>();
                map.put("ImageID", x.getString("ImageID"));
                map.put("ImageDesc", x.getString("ImageDesc"));
                map.put("ImagePath", x.getString("ImagePath"));
                AppArrList.add(map);
            }

        }

        catch (JSONException e)
        {
            e.printStackTrace();
        }

        String path ="http://analog-design.net/WORKAREA/WEBSITE/reservation/luba_74800_1.jpg";

        lstView1.setAdapter(new ImageAdapter(this,AppArrList));
        final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);


    }

    private class JSONParse extends AsyncTask<String, String, String> // JSONObject
    {

        @Override
        protected void onPreExecute()
        {
        }

        @Override
        protected String doInBackground(String... args) // JSONObject
        {
            JSONParser jParser = new JSONParser();

            // Getting JSON from URL
            //JSONObject json = jParser.getJSONFromUrl();
            //return json;
            String json = jParser.getJSONFromUrl();
            return json;

        }

        @Override
        protected void onPostExecute(String json) // JSONObject
        {
            super.onPostExecute(json);
            //store(json);
/*
            pipo = json;
            pipo = "tartuffe";
            Log.i("+++++++", pipo);

            try
            {
                JSONObject jObj = null;
                jObj = new JSONObject(json);
                element = jObj.getJSONArray("result");

                HashMap<String, String> map;
                final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();

                for(int i = 0; i < element.length(); i++)
                {
                    JSONObject x = element.getJSONObject(i);
                    map = new HashMap<String, String>();
                    map.put("ImageID", x.getString("ImageID"));
                    map.put("ImageDesc", x.getString("ImageDesc"));
                    map.put("ImagePath", x.getString("ImagePath"));
                    MyArrList.add(map);
                }

                AppArrList = MyArrList;


                // Storing  JSON item in a Variable
                //String id = c.getString("ImageID");
                //String name = c.getString("ImageDesc");
                //String email = c.getString("ImagePath");

                // lstView1.setAdapter(new ImageAdapter(this,MyArrList));
                //final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);

            }

            catch (JSONException e)
            {
                e.printStackTrace();
            }
*/


        }

    }


    public void store(String s)
    {
        pipo = s;
    }


    public class ImageAdapter extends BaseAdapter
    {
        private Context context;
        private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

        public ImageAdapter(Context c, ArrayList<HashMap<String, String>> list)
        {
            context = c;
            MyArr = list;
        }

        public int getCount()
        {
            return MyArr.size();
        }

        public Object getItem(int position)
        {
            return position;
        }

        public long getItemId(int position)
        {
            return position;
        }
        public View getView(int position, View convertView, ViewGroup parent)
        {

            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if (convertView == null)
            {
                convertView = inflater.inflate(R.layout.activity_column, null);
            }

            // ColImage
            ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
            imageView.getLayoutParams().height = 100;
            imageView.getLayoutParams().width = 100;
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

            try
            {
                imageView.setImageBitmap(loadBitmap(MyArr.get(position).get("ImagePath")));
            }

            catch (Exception e)
            {
                // When Error
                imageView.setImageResource(android.R.drawable.ic_menu_report_image);
            }

            // ColPosition
            TextView txtPosition = (TextView) convertView.findViewById(R.id.ColImgID);
            txtPosition.setPadding(10, 0, 0, 0);
            txtPosition.setText("ID : " + MyArr.get(position).get("ImageID"));

            // ColPicname
            TextView txtPicName = (TextView) convertView.findViewById(R.id.ColImgDesc);
            txtPicName.setPadding(50, 0, 0, 0);
            txtPicName.setText("Desc : " + MyArr.get(position).get("ImageDesc"));

            return convertView;

        }

    }

    public static Bitmap loadBitmap(String url)
    {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;

        int IO_BUFFER_SIZE = 4 * 1024;

        // NetworkOnMainThreadException  attention

        try
        {
            in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in, out);
            out.flush();

            final byte[] data = dataStream.toByteArray();
            BitmapFactory.Options options = new BitmapFactory.Options();
            //options.inSampleSize = 1;

            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
        }

        catch (IOException e)
        {
            Log.e(TAG, "Could not load Bitmap from: " + url);
        }

        finally
        {
            closeStream(in);
            closeStream(out);
        }

        return bitmap;
    }

    private static void closeStream(Closeable stream)
    {
        if (stream != null)
        {
            try
            {
                stream.close();
            }

            catch (IOException e)
            {
                android.util.Log.e("TAG", "Could not close stream", e);
            }
        }
    }

    private static void copy(InputStream in, OutputStream out) throws IOException
    {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;

        while ((read = in.read(b)) != -1)
        {
            out.write(b, 0, read);
        }
    }


}

class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser()
    {

    }

    public  String getJSONFromUrl() // JSONObject
    {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://analog-design.net/WORKAREA/WEBSITE/reservation/query02.php");

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            json = sb.toString();
        }

        catch (Exception e)
        {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
/*
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
*/

        return  json;

    }
}