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.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
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.util.ArrayList;
import java.util.HashMap;

public class splash extends Activity {


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

    private static int SPLASH_TIME_OUT = 3000;

    SQLiteDatabase myDB;


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

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


        myDB.execSQL("CREATE TABLE IF NOT EXISTS t_setting" +
                " (" +
                " set_id INTEGER  PRIMARY KEY ASC," +
                " set_user_name VARCHAR default '', " +
                " set_user_id VARCHAR default '', " +
                " set_token VARCHAR default '', " +
                " set_fcm_token VARCHAR default '', " +
                " set_login_datetime VARCHAR default '' " +



                ");");


        //update :
        if(!isFieldExist(myDB, "t_setting", "set_login_datetime")) {
            //add field:
            myDB.execSQL("ALTER TABLE t_setting " +
                    "  ADD set_login_datetime VARCHAR default '' ; ");

        }

        //update :
        if(!isFieldExist(myDB, "t_setting", "set_fcm_token")) {
            //add field:
            myDB.execSQL("ALTER TABLE t_setting " +
                    "  ADD set_fcm_token VARCHAR default '' ; ");

        }







        String Query = "Select * from t_setting ; ";
        Cursor cursor = myDB.rawQuery(Query, null);
        if (cursor.getCount() <= 0) {
            cursor.close();


            //create mode
            myDB.execSQL("INSERT INTO "
                    + "t_setting"
                    + " ("
                    + " set_user_name, "
                    + " set_user_id, "
                    + " set_token "
                    + ") "
                    + " VALUES "
                    + " ("
                    + "'', "
                    + "'', "
                    + "''  "
                    + ");");

        }






        new Handler().postDelayed(new Runnable() {

            /*
             * Showing splash screen with a timer. This will be useful when you
             * want to show case your app logo / company
             */

            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app main activity


                Intent act_login = new Intent(splash.this, login.class);
                startActivity(act_login);
                finish();




            }
        }, SPLASH_TIME_OUT);



        //new ping_async().execute();



    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();

    }







    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(splash.this);
            // Set progressbar title
            pDialog.setTitle(R.string.dialog_loading);
            // Set progressbar message
            pDialog.setMessage(splash.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 boolean isFieldExist(SQLiteDatabase dbName, String tableName, String fieldName)
    {
        boolean isExist = true;

        Cursor res = dbName.rawQuery("select * from "+tableName+"; ",null);
        int value = res.getColumnIndex(fieldName);

        if(value == -1)
        {
            isExist = false;
        }
        return isExist;
    }




}
