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.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;

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



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

    SQLiteDatabase myDB;


    Button button_delete_cart_item;





    TextView textView_code;
    TextView textView_name;
    TextView textView_product_code;
    TextView textView_product_name;


    String cart_code = "";
    String cart_name = "";
    String cart_product_code = "";
    String cart_product_name = "";




    String this_cart_id  = "";

    String scanned_code = "";

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


        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_cart_id = extras.getString("id");


        }



        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle("Cart 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);







        textView_code = findViewById(R.id.textView_code);
        textView_name = findViewById(R.id.textView_name);
        textView_product_code = findViewById(R.id.textView_product_code);
        textView_product_name = findViewById(R.id.textView_product_name);





        button_delete_cart_item = findViewById(R.id.button_delete_cart_item);
        button_delete_cart_item.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {

                new delete_cart_async().execute();


            }
        });


        new get_cart_item_async().execute();


    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();
        finish();


    }









    public class get_cart_item_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(cart_item.this);
            // Set progressbar title
            pDialog.setTitle(R.string.dialog_loading);
            // Set progressbar message
            pDialog.setMessage(cart_item.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_cart_item.php" +
                    "?u=" + Uri.encode(current_user_id) +
                    "&t=" + Uri.encode(current_token) +
                    "&id=" + Uri.encode(this_cart_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("cart_item");

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



                            cart_code = oneObject.getString("code");
                            cart_name = oneObject.getString("name");
                            cart_product_code = oneObject.getString("product_code");
                            cart_product_name = oneObject.getString("product_name");





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


                            //map = new HashMap<String, String>();
                            //map.put("name", oneObject.getString("name"));
                            //map.put("code", oneObject.getString("code"));
                            //map.put("status", oneObject.getString("status"));
                            //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();
            }



            if(server_info_success)
            {


                    //do thing here

                textView_code.setText(cart_code);
                textView_name.setText(cart_name);
                textView_product_code.setText(cart_product_code);
                textView_product_name.setText(cart_product_name);






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




        }


    }






    public class delete_cart_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(cart_item.this);
            // Set progressbar title
            pDialog.setTitle(R.string.dialog_loading);
            // Set progressbar message
            pDialog.setMessage(cart_item.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/delete_cart.php" +
                    "?u=" + Uri.encode(current_user_id) +
                    "&t=" + Uri.encode(current_token) +
                    "&id=" + Uri.encode(this_cart_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("delete_cart");

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

                finish();


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




        }


    }






}
