package my.com.pcloud.salesapplite;

import android.app.ProgressDialog;
import android.content.Intent;
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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;

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 MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {






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

    String current_fcm_token = "";


    SQLiteDatabase myDB;
    String current_fragment_tag;

    NavigationView navigationView;
    ActionBarDrawerToggle toggle;






    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


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

            current_fcm_token = String.valueOf(cursor_active.getString(cursor_active.getColumnIndex("set_fcm_token")));



        }
        cursor_active.close();





        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });



        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();



        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        View header = navigationView.getHeaderView(0);

        //View view=navigationView.inflateHeaderView(R.layout.nav_header_main);
        TextView master_user_name = (TextView)header.findViewById(R.id.master_user_name);
        TextView master_user_email = (TextView)header.findViewById(R.id.master_user_email);



        master_user_name.setText("Welcome");
        master_user_email.setText(current_user_name);








        String menuFragment = getIntent().getStringExtra("menuFragment");

        FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
        tx.replace(R.id.flContent, new f_home(),"F_HOME");
        tx.commit();




        //when come to homepage hide the the toolbar
        this.getSupportActionBar().hide();
        //this.getSupportActionBar().setBackgroundDrawable(null);
        //this.getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));




        new ping_async().execute();








    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            drawer.openDrawer(GravityCompat.START);
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();


        String fragment_tag="";
        Fragment fragment = null;

        Class fragmentClass;


        if (id == R.id.nav_home) {
            fragmentClass = f_home.class;
            fragment_tag="F_HOME";

            this.getSupportActionBar().hide();
            //when come to homepage hide the the toolbar



        } else if (id == R.id.nav_customer) {
            fragmentClass = f_customer.class;
            fragment_tag = "F_CUSTOMER";

            this.getSupportActionBar().show();
            this.getSupportActionBar().setTitle(R.string.menu_customer);
            //when come to homepage hide the the toolbar


        } else if (id == R.id.nav_report) {
            fragmentClass = f_report.class;
            fragment_tag = "F_REPORT";

            this.getSupportActionBar().show();
            this.getSupportActionBar().setTitle(R.string.menu_report);
            //when come to homepage hide the the toolbar

        } else if (id == R.id.nav_report2) {
            fragmentClass = f_report2.class;
            fragment_tag = "F_REPORT2";

            this.getSupportActionBar().show();
            this.getSupportActionBar().setTitle(R.string.menu_report2);
            //when come to homepage hide the the toolbar


        } else if (id == R.id.nav_setting) {
            fragmentClass = f_setting.class;
            fragment_tag = "F_SETTING";

            this.getSupportActionBar().show();
            this.getSupportActionBar().setTitle(R.string.menu_setting);
            //when come to homepage hide the the toolbar


        }
        else {
            fragmentClass = f_about.class;
            fragment_tag="F_ABOUT";

            this.getSupportActionBar().show();
            this.getSupportActionBar().setTitle(R.string.menu_about);
        }






        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }



        //DrawerLayout drawer = findViewById(R.id.drawer_layout);
        //drawer.closeDrawer(GravityCompat.START);
        //return true;


        current_fragment_tag = fragment_tag;

        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment,fragment_tag).commit();


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;

    }



    public void openNaviDrawer() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.openDrawer(GravityCompat.START);
    }





    public void kick_out()
    {



        //create mode
        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);



        Toast.makeText(this, "Kicked Out", Toast.LENGTH_LONG).show();



    }



    public class update_token_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 token_update_ok = false;


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

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



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



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

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




        }


    }








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

        }


    }















}
