package my.com.pcloud.salesapplite;

import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
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.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.Toast;

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

public class f_home extends Fragment {

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

    SQLiteDatabase myDB;



    ImageButton MenuButton;


    ProgressDialog progressDialog;

    WebView mWebview;



    public static Fragment newInstance(Context context) {

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

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





        MenuButton = (ImageButton) view.findViewById(R.id.MenuButton);
        MenuButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ((MainActivity) getActivity()).openNaviDrawer();


            }
        });















        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("Loading");
        progressDialog.show();


        mWebview  = view.findViewById(R.id.wb_report);





        mWebview.setWebViewClient(new WebViewClient() {


            @SuppressWarnings("deprecation")
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

                Toast.makeText(getActivity(), description, Toast.LENGTH_SHORT).show();

            }





            @Override
            public void onPageFinished(WebView view, final String url) {

                progressDialog.cancel();


            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                progressDialog.show();
            }




            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
                // Redirect to deprecated method, so you can use it in all SDK versions
                onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
            }





            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                // This method did not appear until 6.0.

                int statusCode = errorResponse.getStatusCode();


                if (request.isForMainFrame()) {


                    if (404 == statusCode || 500 == statusCode) {
                        view.loadUrl("about:blank");// Avoid default error interfaces
                        Toast.makeText(getActivity(), "Fail to load content", Toast.LENGTH_SHORT).show();
                    }
                }

            }


        });


        String report_link = "" + getString(R.string.system_cloud_server_url) + "apiv1/html_dashboard.php" +
                "?u=" + Uri.encode(current_user_id) +
                "&t=" + Uri.encode(current_token) +
                "";



        mWebview.getSettings().setAllowUniversalAccessFromFileURLs(true);
        mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
        mWebview.getSettings().setDomStorageEnabled(true);



        mWebview.loadUrl(report_link);










        //new ping_async().execute();
        //new get_home_async().execute();



        return view;
    }

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




    }


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



    }




    @Override
    public void onResume() {
        Log.e("DEBUG", "onResume of LoginFragment");
        super.onResume();

        //new get_home_async().execute();

    }




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

        @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/home.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);



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

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



                            //user_id = oneObject.getString("user_id");




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





            }
            else
            {



            }

        }


    }













    public static final String md5(final String s) {
        final String MD5 = "MD5";
        try {
            // Create MD5 Hash
            MessageDigest digest = 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 "";
    }




}
