package my.com.pcloud.salesapplite;

import android.app.ProgressDialog;
import android.content.Context;
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.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

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_setting extends Fragment {


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

    SQLiteDatabase myDB;


    String user_password="";



    EditText et_password1;
    EditText et_password2;

    Button button_save;


    public static Fragment newInstance(Context context) {

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.f_setting, 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();



        et_password1 = view.findViewById(R.id.editText_password1);
        et_password2 = view.findViewById(R.id.editText_password2);





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

            public void onClick(View view) {

                user_password="";


                String password1 = et_password1.getText().toString();
                String password2 = et_password2.getText().toString();



                String error_msg="";


                if(password1.equals(""))
                {
                    error_msg = error_msg + " New Password is empty. ";
                }

                if(password2.equals(""))
                {
                    error_msg = error_msg + " Repeat New Password is empty. ";
                }

                if(!password2.equals(password1))
                {
                    error_msg = error_msg + " Both Passwords not match. ";
                }




                if(error_msg.equals(""))
                {

                    user_password=password1;

                    new save_new_password_async().execute();


                }
                else
                {

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

                }




            }
        });





        //new ping_async().execute();

        return view;
    }

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

    }












    public class save_new_password_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(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/save_password.php" +
                    "?u=" + Uri.encode(current_user_id) +
                    "&t=" + Uri.encode(current_token) +
                    "&pwd=" + Uri.encode(user_password) +


                    "";




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

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


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



            if(server_action_success)
            {

                Toast toast = Toast.makeText(getContext(), "Password Changed", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER | Gravity.CENTER, 0, 10);
                toast.show();





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






        }


    }


}
