package my.com.pcloud.salesapplite;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

public class f_customer extends Fragment {


    String current_user_name="";
    String current_user_id="";
    String current_token="";

    SQLiteDatabase myDB;

    ListView listview_main;

    String search_string="";


    SearchView searchView;



    public static Fragment newInstance(Context context) {

        f_customer f = new f_customer();
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.f_customer, null);


        myDB = getActivity().openOrCreateDatabase("app_db", Context.MODE_PRIVATE, null);

        Cursor cursor_active = myDB.rawQuery("select * from t_setting ", null);
        if (null != cursor_active && cursor_active.moveToFirst()) {

            current_user_name = String.valueOf(cursor_active.getString(cursor_active.getColumnIndex("set_user_name")));
            current_user_id = String.valueOf(cursor_active.getString(cursor_active.getColumnIndex("set_user_id")));
            current_token = String.valueOf(cursor_active.getString(cursor_active.getColumnIndex("set_token")));


        }
        cursor_active.close();



        listview_main = view.findViewById(R.id.listview_main);


        searchView = (SearchView) view.findViewById(R.id.searchview_main);


        //------------------------single item click-------------------------------
        AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                final TextView textView_id = (TextView) view.findViewById(R.id.textView_id);
                final TextView textView_code = (TextView) view.findViewById(R.id.textView_code);
                final TextView textView_name = (TextView) view.findViewById(R.id.textView_name);


                Intent i = new Intent(getContext(), customer_page.class);
                i.putExtra("id", textView_id.getText().toString());
                i.putExtra("code", textView_code.getText().toString());
                i.putExtra("name", textView_name.getText().toString());
                startActivity(i);

            }
        };

        listview_main.setOnItemClickListener(itemClickListener);




        search_string="";

        display_list(search_string);







        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {


                search_string=query;

                display_list(search_string);

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                //    adapter.getFilter().filter(newText);
                return false;
            }
        });






        FloatingActionButton myFab = (FloatingActionButton) view.findViewById(R.id.fab_add_new);
        myFab.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Intent i = new Intent(getContext(), customer_form.class);
                startActivity(i);

            }
        });




        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }


    @Override
    public void onResume() {
        super.onResume();
        new get_list_async().execute();

    }




    public void display_list(String search_string) {


        new get_list_async().execute();


    }




    public class get_list_async extends AsyncTask<String, Integer, Void> {


        ProgressDialog pDialog;

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

        boolean connection_ok = false;
        boolean valid_session = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = new ProgressDialog(getContext());
            // Set progressbar title
            pDialog.setTitle(R.string.dialog_loading);
            // Set progressbar message
            pDialog.setMessage(getActivity().getString(R.string.dialog_please_wait));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.setProgressStyle(pDialog.STYLE_SPINNER);
            pDialog.show();

            connection_ok = false;

        }


        @Override
        protected Void doInBackground(String... strings) {

            String cloud_link = "" + getString(R.string.system_cloud_server_url) + "apiv1/get_customer_list.php" +
                    "?u=" + Uri.encode(current_user_id) +
                    "&t=" + Uri.encode(current_token) +
                    "&search=" + Uri.encode(search_string) +

                    "";

            try {

                Log.d("GetDocument", "Start");

                try {

                    //====================================
                    //connect to json data site:
                    Log.d("GetDocument", "Connect: " + cloud_link);
                    URL url = new URL(cloud_link);

                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    InputStream is = connection.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));

                    Log.d("GetDocument", "Connected");

                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                    line = sb.toString();
                    connection.disconnect();
                    is.close();
                    sb.delete(0, sb.length());
                    //====================================


                    String json_string = line;
                    Log.d("GetDocument", "Content Return: " + json_string);
                    JSONObject jObject = new JSONObject(json_string);


                    //------------------ SESSION-----------------------------------------------
                    JSONArray jArray_content_session = jObject.getJSONArray("session");

                    for (int i = 0; i < jArray_content_session.length(); i++) {
                        Log.d("GetDocument", "Processing Object: " + String.valueOf(i));
                        try {
                            JSONObject oneObject = jArray_content_session.getJSONObject(i);


                            if (oneObject.getString("status").equals("YES")) {
                                valid_session = true;
                            }
                            connection_ok = true;


                        } catch (JSONException e) {
                            Log.d("GetDocument", "JSON Error" + e);
                        }
                    }


                    //------------------ transaction-----------------------------------------------
                    JSONArray jArray_content_document = jObject.getJSONArray("list");

                    for (int i = 0; i < jArray_content_document.length(); i++) {
                        Log.d("GetDocument", "Processing Object: " + String.valueOf(i));
                        try {
                            JSONObject oneObject = jArray_content_document.getJSONObject(i);



                            map = new HashMap<String, String>();
                            map.put("name", oneObject.getString("name"));
                            map.put("code", oneObject.getString("code"));
                            map.put("id", oneObject.getString("id"));
                            mylist.add(map);


                        } catch (JSONException e) {
                            Log.d("GetDocument", "JSON Error" + e);
                        }
                    }






                } catch (MalformedURLException e) {
                    Log.e("GetDocument", "URL Malformed ", e);
                    e.printStackTrace();

                } catch (ProtocolException e) {
                    Log.e("GetDocument", "Protocal Exception ", e);
                    e.printStackTrace();
                } catch (IOException e) {
                    Log.e("GetDocument", "IO Exception ", e);
                    e.printStackTrace();
                } catch (Exception e) {
                    Log.e("GetDocument", "Exception ", e);
                    e.printStackTrace();
                }

                Log.d("GetDocument", "Done");

            } catch (Exception q) {
                Log.e("GetDocument", "Connection Fail: ", q);
                //Toast.makeText(this, "Connection Fail ", Toast.LENGTH_LONG).show();
            }

            return null;
        }


        @Override
        protected void onPostExecute(Void args) {
            pDialog.dismiss();

            if (!valid_session) {


                ((MainActivity) getActivity()).kick_out();


            }


            if (!connection_ok) {
                Toast toast = Toast.makeText(getContext(), getString(R.string.dialog_fail_connect) + " " + getString(R.string.system_cloud_server_url), Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER | Gravity.CENTER, 0, 10);
                toast.show();
            }


            //fill_list_view();


            SimpleAdapter productListAdapter = new SimpleAdapter(getActivity(),
                    mylist,
                    R.layout.row_customer,
                    new String[]{"id", "code","name"},
                    new int[]{R.id.textView_id,R.id.textView_code,R.id.textView_name}
            );
            listview_main.setAdapter(productListAdapter);







        }


    }


}
