package my.com.pcloud.salesapplite;


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

import androidx.appcompat.widget.Toolbar;

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 customer_purchase extends Activity {



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

    SQLiteDatabase myDB;

    String this_customer_id="";
    String this_customer_name="";
    String this_customer_code="";


    ListView listview_main;


    String scanned_code = "";

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


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



        Cursor cursor_active = myDB.rawQuery("select * from t_setting " +
                "    ", null);

        if (null != cursor_active && cursor_active.moveToFirst()) {

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






        Bundle extras = getIntent().getExtras();
        if(extras == null) {

        } else {


            this_customer_id = extras.getString("id");
            this_customer_code = extras.getString("code");
            this_customer_name = extras.getString("name");



        }



        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle("Purchased Item");

        mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);


        mToolbar.setTitleTextColor(Color.WHITE);

        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });



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





        listview_main = findViewById(R.id.listview_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(customer_purchase.this, document_page.class);
                i.putExtra("id", textView_id.getText().toString());
                startActivity(i);

            }
        };

        listview_main.setOnItemClickListener(itemClickListener);












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



                //change to invoice screen:


                Intent i = new Intent(customer_purchase.this, customer_purchase_cart.class);
                i.putExtra("id", this_customer_id);
                i.putExtra("code", this_customer_code);
                startActivityForResult(i,1);





            }
        });




        new get_purchase_async().execute();



    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();
        finish();


    }


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

        new get_purchase_async().execute();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1) {
            if(resultCode == Activity.RESULT_OK){
                String result=data.getStringExtra("scanned_code");

                scanned_code =result;

                new add_purchase_async().execute();

            }
            if (resultCode == Activity.RESULT_CANCELED) {

            }
        }
    }//onActivityResult









    public class get_purchase_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;
        boolean server_info_success= false;




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

            pDialog = new ProgressDialog(customer_purchase.this);
            // Set progressbar title
            pDialog.setTitle(R.string.dialog_loading);
            // Set progressbar message
            pDialog.setMessage(customer_purchase.this.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_purchase.php" +
                    "?u=" + Uri.encode(current_user_id) +
                    "&t=" + Uri.encode(current_token) +
                    "&id=" + Uri.encode(this_customer_id) +
                    "";

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




                    //------------------ Status-----------------------------------------------
                    JSONArray jArray_content_document = jObject.getJSONArray("document_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);



                            //user_name = oneObject.getString("name");


                            map = new HashMap<String, String>();
                            map.put("doc_no", oneObject.getString("doc_no"));
                            map.put("date", oneObject.getString("date"));
                            map.put("amount", oneObject.getString("amount"));
                            map.put("id", oneObject.getString("id"));
                            mylist.add(map);



                            server_info_success = true;

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



                myDB.execSQL("update t_setting  "
                        + " set "

                        + " set_user_name = '', "
                        + " set_user_id = '', "
                        + " set_token = '' "

                        + ";");


                finish();
                Intent act_open_entry = new Intent(getApplicationContext(), login.class);
                startActivity(act_open_entry);



            }





            if(!connection_ok)
            {
                Toast toast = Toast.makeText(getApplicationContext(), 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();
            }



            SimpleAdapter productListAdapter = new SimpleAdapter(customer_purchase.this,
                    mylist,
                    R.layout.row_document,
                    new String[]{"id", "doc_no","date","amount"},
                    new int[]{R.id.textView_id,R.id.textView_doc_no,R.id.textView_date,R.id.textView_amount}
            );
            listview_main.setAdapter(productListAdapter);







        }


    }






    public class add_purchase_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;
        boolean server_action_success= false;

        String server_message="";


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

            pDialog = new ProgressDialog(customer_purchase.this);
            // Set progressbar title
            pDialog.setTitle(R.string.dialog_loading);
            // Set progressbar message
            pDialog.setMessage(customer_purchase.this.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/add_customer_purchase.php" +
                    "?u=" + Uri.encode(current_user_id) +
                    "&t=" + Uri.encode(current_token) +
                    "&id=" + Uri.encode(this_customer_id) +
                    "&code=" + Uri.encode(scanned_code) +

                    "";

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




                    //------------------ Status-----------------------------------------------
                    JSONArray jArray_content_document = jObject.getJSONArray("add_purchase");

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



                            if(oneObject.getString("status").equals("YES"))
                            {
                                server_action_success = true;
                            }
                            else
                            {
                                server_message=oneObject.getString("message");
                            }








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



                myDB.execSQL("update t_setting  "
                        + " set "

                        + " set_user_name = '', "
                        + " set_user_id = '', "
                        + " set_token = '' "

                        + ";");


                finish();
                Intent act_open_entry = new Intent(getApplicationContext(), login.class);
                startActivity(act_open_entry);



            }





            if(!connection_ok)
            {
                Toast toast = Toast.makeText(getApplicationContext(), 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();
            }




            if(server_action_success)
            {


                //refresh list:
                new get_purchase_async().execute();


            }
            else
            {
                Toast toast = Toast.makeText(getApplicationContext(), "Fail: "+server_message, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER | Gravity.CENTER, 0, 10);
                toast.show();
            }




        }


    }






}
