package my.com.pcloud.salesapplite;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
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.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;

public class login 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_password="";

    SharedPreferences pref;
    SharedPreferences.Editor editor;

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



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


        pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
        editor = pref.edit();


        userIDTextInputEditText = findViewById(R.id.userIDTextInputEditText);
        passwordTextInputEditText = findViewById(R.id.passwordTextInputEditText);



        userIDTextInputEditText.setText(pref.getString("username", null));



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

            public void onClick(View view) {



                user_name = userIDTextInputEditText.getText().toString();
                user_password = passwordTextInputEditText.getText().toString();



                String error_msg = "";

                if(user_name.equals(""))
                {
                    error_msg = error_msg + "Login ID is empty\n";
                }


                if(user_password.equals(""))
                {
                    error_msg = error_msg + "Password is empty\n";

                }



                if(error_msg.equals(""))
                {
                    login_check();



                }
                else
                {

                    Toast.makeText(getApplicationContext(), error_msg,
                            Toast.LENGTH_LONG).show();



                }









            }
        });





        //new ping_async().execute();



    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();

    }




    public void login_check()
    {


        new login_check_async().execute();


    }







    public class login_check_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 login_succes = false;
        String server_message="";


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

            pDialog = new ProgressDialog(login.this);
            // Set progressbar title
            pDialog.setTitle(R.string.dialog_loading);
            // Set progressbar message
            pDialog.setMessage(login.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/login.php" +
                    "?u=" + Uri.encode(user_name) +
                    "&p=" + Uri.encode(md5(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);

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

                    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);
                            Log.d("GetDocument","Status: "+oneObject.getString("status"));

                            if(oneObject.getString("status").equals("SUCCESS"))
                            {
                                login_succes = true;
                                //update token here:


                                //create mode
                                myDB.execSQL("update t_setting  "
                                        + " set "

                                        + " set_user_name = '"+user_name+"', "
                                        + " set_user_id = '"+oneObject.getString("user_id")+"', "
                                        + " set_token = '"+oneObject.getString("token")+"' "

                                        + ";");





                            }
                            else
                            {

                            }

                            server_message = oneObject.getString("message");

                            connection_ok = 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(!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(login_succes)
            {


                editor.putString("username", user_name);
                editor.commit();


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




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



            }







        }


    }








    public class ping_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;

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

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

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

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

                    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);
                            Log.d("GetDocument","Status: "+oneObject.getString("status"));

                            if(oneObject.getString("status").equals("SUCCESS"))
                            {
                                connection_ok=true;
                            }
                            else
                            {

                            }

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

        }


    }








    public static final String md5(final String s) {
        final String MD5 = "MD5";
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest
                    .getInstance(MD5);
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            // Create Hex String
            StringBuilder hexString = new StringBuilder();
            for (byte aMessageDigest : messageDigest) {
                String h = Integer.toHexString(0xFF & aMessageDigest);
                while (h.length() < 2)
                    h = "0" + h;
                hexString.append(h);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


}
