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.EditText;
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 customer_form extends Activity {


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


    EditText et_user_name;
    //EditText et_user_code;
    EditText et_user_email;
    EditText et_user_phone;
    EditText et_user_address;

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

    Button button_save;


    String form_mode="";


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


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




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

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






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



        form_mode="CREATE";


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


            form_mode="EDIT";

            //mToolbar.setTitle(this_customer_name);



        }


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




        et_user_name = findViewById(R.id.editText_name);
        //et_user_code = findViewById(R.id.editText_code);
        et_user_email = findViewById(R.id.editText_email);
        et_user_phone = findViewById(R.id.editText_phone);
        et_user_address = findViewById(R.id.editText_address);







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

            public void onClick(View view) {



                user_name = et_user_name.getText().toString();
                //user_code = et_user_code.getText().toString();
                user_email = et_user_email.getText().toString();
                user_phone = et_user_phone.getText().toString();
                user_address = et_user_address.getText().toString();



                String error_msg="";


                /*
                if(user_code.equals(""))
                {
                    error_msg = error_msg + " Code is empty. ";
                }
                */


                if(user_name.equals(""))
                {
                    error_msg = error_msg + " Name is empty. ";
                }




                if(user_phone.equals(""))
                {
                    error_msg = error_msg + " Phone is empty. ";
                }


                if(user_email.equals(""))
                {
                    error_msg = error_msg + " Email is empty. ";
                }







                if(error_msg.equals(""))
                {

                    new save_customer_async().execute();


                }
                else
                {

                    Toast toast = Toast.makeText(getApplicationContext(), error_msg, Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER | Gravity.CENTER, 0, 10);
                    toast.show();

                }




            }
        });














        if(form_mode.equals("EDIT"))
        {
            new get_account_async().execute();
        }



    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();
        finish();


    }





    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_form.this);
            // Set progressbar title
            pDialog.setTitle(R.string.dialog_loading);
            // Set progressbar message
            pDialog.setMessage(customer_form.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)
            {





                et_user_name.setText(user_name);
                //et_user_code.setText(user_code);
                et_user_email.setText(user_email);
                et_user_phone.setText(user_phone);
                et_user_address.setText(user_address);


            }



        }


    }











    public class save_customer_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_form.this);
            // Set progressbar title
            pDialog.setTitle(R.string.dialog_loading);
            // Set progressbar message
            pDialog.setMessage(customer_form.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/save_customer.php" +
                    "?u=" + Uri.encode(current_user_id) +
                    "&t=" + Uri.encode(current_token) +
                    "&mode=" + Uri.encode(form_mode) +
                    "&id=" + Uri.encode(this_customer_id) +


                    "&name=" + Uri.encode(user_name) +

                    "&email=" + Uri.encode(user_email) +
                    "&phone=" + Uri.encode(user_phone) +
                    "&address=" + Uri.encode(user_address) +

                    "";


            //"&code=" + Uri.encode(user_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("save_customer");

                    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_action_success=false;


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

                Toast toast = Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER | Gravity.CENTER, 0, 10);
                toast.show();


                finish();


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






        }


    }








}
