package my.com.pcloud.salesapplite;


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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
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 customer_page extends AppCompatActivity {


    TextView textView_menu_login;
    TextView textView_menu_signup;
    Button btn_continue;

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

    SQLiteDatabase myDB;

    EditText userIDTextInputEditText;
    EditText passwordTextInputEditText;

    String user_name="";
    String user_code="";
    String user_email="";
    String user_phone="";
    String user_address="";


    TextView tv_user_name;
    TextView tv_user_code;
    TextView tv_user_email;
    TextView tv_user_phone;
    TextView tv_user_address;

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


    Button button_purchase_item_product;
    Button button_purchase_item;
    Button button_completed_treatment;






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




        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle("Customer Info");

        //create 3 dot menu
        setSupportActionBar(mToolbar);

        mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);


        mToolbar.setTitleTextColor(Color.WHITE);


        //create back button
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {



                Log.d("test","test");



                finish();
            }
        });

        Log.d("test","test");







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



        }


        user_name=this_customer_name;
        user_code=this_customer_code;
        user_email="";
        user_phone="";
        user_address="";




        tv_user_name = findViewById(R.id.textView_full_name);
        tv_user_code = findViewById(R.id.textView_code);
        tv_user_email = findViewById(R.id.textView_email);
        tv_user_phone = findViewById(R.id.textView_phone);
        tv_user_address = findViewById(R.id.textView_address);











        /*


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

            public void onClick(View view) {

                Intent i = new Intent(customer_page.this, customer_purchase_product.class);
                i.putExtra("id", this_customer_id);
                i.putExtra("code", this_customer_code);
                i.putExtra("name", this_customer_name);
                startActivity(i);


            }
        });


         */



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

            public void onClick(View view) {

                Intent i = new Intent(customer_page.this, customer_purchase.class);
                i.putExtra("id", this_customer_id);
                i.putExtra("code", this_customer_code);
                i.putExtra("name", this_customer_name);
                startActivity(i);


            }
        });





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

            public void onClick(View view) {

                Intent i = new Intent(customer_page.this, customer_use.class);
                i.putExtra("id", this_customer_id);
                i.putExtra("code", this_customer_code);
                i.putExtra("name", this_customer_name);
                startActivity(i);


            }
        });














        new get_account_async().execute();



    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();
        finish();


    }

    @Override
    public void onResume() {

        super.onResume();


        new get_account_async().execute();


    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.customer_page_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) {
        case R.id.edit:

            Intent i1 = new Intent(customer_page.this, customer_form.class);
            i1.putExtra("id", this_customer_id);
            i1.putExtra("code", this_customer_code);
            i1.putExtra("name", this_customer_name);
            startActivity(i1);


            return(true);



        case R.id.view_card:

            Intent i2 = new Intent(customer_page.this, customer_card.class);
            i2.putExtra("id", this_customer_id);
            i2.putExtra("code", this_customer_code);
            i2.putExtra("name", this_customer_name);
            startActivity(i2);

            return(true);

        }



        return(super.onOptionsItemSelected(item));
    }



    public class get_account_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_page.this);
            // Set progressbar title
            pDialog.setTitle(R.string.dialog_loading);
            // Set progressbar message
            pDialog.setMessage(customer_page.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_page.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("account_info");

                    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");
                            user_code= oneObject.getString("code");;
                            user_email= oneObject.getString("email");
                            user_phone= oneObject.getString("phone");
                            user_address= oneObject.getString("address");



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




                tv_user_name.setText(user_name);
                tv_user_code.setText(user_code);
                tv_user_email.setText(user_email);
                tv_user_phone.setText(user_phone);
                tv_user_address.setText(user_address);


            }



        }


    }










}
