package com.b2lmobitech.spottest;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.b2lmobitech.spottest.network.MyRequestQueue;
import com.b2lmobitech.spottest.network.URL;
import com.b2lmobitech.spottest.utils.MySnackbar;
import com.b2lmobitech.spottest.utils.Preference;
import com.google.firebase.iid.FirebaseInstanceId;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity {

    EditText userEmail,userPassword;
    private String build_code,versionname,installedtime,versioncode,updatedtime;

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

    private void getWidgets(){
        userEmail=findViewById(R.id.userEmail);
        userPassword=findViewById(R.id.userPassword);

        findViewById(R.id.signinButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isValid()){
                    build_code = "";
                    versionname = "";
                    installedtime = "";
                    versioncode = "";
                    updatedtime = "";
                    signIn();
                }
            }
        });

        findViewById(R.id.registerNow).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(),RegisterActivity.class));
            }
        });

        findViewById(R.id.forgotPassword).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(),ForgotPassword.class));
            }
        });

    }

    private boolean isValid(){
        MySnackbar snackbar=MySnackbar.getInstance(this);

        if(userEmail.getText().toString().isEmpty()){
            snackbar.show("Enter Id");
            return false;
        }

        if(userPassword.getText().toString().isEmpty()){
            snackbar.show("Enter Password");
            return false;
        }else if(userPassword.getText().toString().length()<6){
            snackbar.show("Password Should Consists atleast 6 characters");
            return false;
        }

        closeKeyboard();
        return true;
    }

    private void closeKeyboard() {
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if(inputManager.isActive()) {
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void signIn() {

        Map<String, String> params = new HashMap<>();
        params.put("pass", userPassword.getEditableText().toString());
        params.put("email", userEmail.getEditableText().toString());
        params.put("deviceid", FirebaseInstanceId.getInstance().getId());
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            askPermission();
            return;
        }
        params.put("imei", ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId());

        MyRequestQueue myRequestQueue=MyRequestQueue.getInstance(this);
        myRequestQueue.addToQueue(URL.USER_LOGIN, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {
                try {
                    signIn(new JSONObject(response));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void signIn(JSONObject jsonObject) throws JSONException {
        if(jsonObject.getInt("s")==1){
            Preference preference=Preference.getInstance(this);
            preference.putString("email",jsonObject.getString("email"));
            preference.putString("name",jsonObject.getString("name"));
            preference.putString("mobile",jsonObject.getString("phone"));
            preference.putString("student_id",jsonObject.getString("student_id"));
            preference.putString("registered_datetime",jsonObject.getString("registered_datetime"));
            preference.putString("reg_no",jsonObject.getString("reg_no"));
           // preference.putString("firebase_token",jsonObject.getString("firebase_token"));
            //---get currentversion---//
            try {
                PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
                long firstinstalltime = packageInfo.firstInstallTime;
                long lastupdateime = packageInfo.lastUpdateTime;
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                build_code= "sdk "+ Build.VERSION.SDK_INT;
                versionname=String.valueOf(packageInfo.versionName);
                installedtime=dateFormat.format(new Date(firstinstalltime));
                updatedtime=dateFormat.format(new Date(lastupdateime));
                versioncode=String.valueOf(packageInfo.versionCode);

//                 Toast.makeText(LoginActivity.this,"current_versionname = "+jsonObject.getString("current_versionname"),Toast.LENGTH_LONG).show();
//                Toast.makeText(LoginActivity.this,"updated_time = "+jsonObject.getString("updated_time"),Toast.LENGTH_LONG).show();
            if(!versionname.equalsIgnoreCase(jsonObject.getString("current_versionname")) || !updatedtime.equalsIgnoreCase(jsonObject.getString("updated_time"))) {// || !firebase_token.equalsIgnoreCase(FirebaseInstanceId.getInstance().getToken()
                updateCurrentVerision();
            }
            else
            {
                startActivity(new Intent(getApplicationContext(),DashboardActivity.class));
                finish();
            }

            } catch (PackageManager.NameNotFoundException e) {
                //e.printStackTrace();
            }
            //---get currentversion---//
//            startActivity(new Intent(getApplicationContext(),DashboardActivity.class));
//            finish();
        }else{
            MySnackbar snackbar=MySnackbar.getInstance(this);
            snackbar.show(jsonObject.getString("m"));
        }
    }

    private void askPermission(){

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

// Add the buttons
        builder.setPositiveButton("GO TO SETTING", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + BuildConfig.APPLICATION_ID)));
            }
        });

        builder.setNegativeButton("CLOSE APP" +
                "", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                finish();
            }
        });

        builder.setTitle("Permissions Required");
        builder.setMessage("Please enable all permissions");
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    private void updateCurrentVerision() {
        Map<String, String> params = new HashMap<>();
        params.put("reg_no", userEmail.getEditableText().toString());
        params.put("installed_time", installedtime);
        params.put("updated_time", updatedtime);
        params.put("current_versionname", versionname);
        params.put("current_versioncode", versioncode);
        params.put("build_code", build_code);
//        Toast.makeText(LoginActivity.this, userEmail.getEditableText().toString(),Toast.LENGTH_LONG).show();
        MyRequestQueue myRequestQueue = MyRequestQueue.getInstance(this);
        myRequestQueue.addToQueue(URL.UPDATE_CURRENTVERSION, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {
                JSONObject json = null;
                try {
                    json = new JSONObject(response);
                    if (json != null) {
//                    Toast.makeText(getApplicationContext(), json.getString("message"), Toast.LENGTH_SHORT).show();
                    if (json.getInt("success") == 1) {
                        //Toast.makeText(getApplicationContext(),json.getString("message"),Toast.LENGTH_SHORT).show();
                        Preference preference = Preference.getInstance(LoginActivity.this);
                        preference.putString("installed_time", installedtime);
                        preference.putString("updated_time", updatedtime);
                        preference.putString("current_versionname", versionname);
                        preference.putString("current_versioncode", versioncode);
                        preference.putString("build_code", build_code);
                        startActivity(new Intent(getApplicationContext(), DashboardActivity.class));
                        finish();
                    } else {
                        Preference preference = Preference.getInstance(LoginActivity.this);
                        preference.putString("student_id", "");
//                        MySnackbar snackbar = MySnackbar.getInstance(LoginActivity.this);
//                        snackbar.show(json.getString("message"));
                        Toast.makeText(LoginActivity.this,json.getString("message"),Toast.LENGTH_LONG).show();
                    }
                }
                else {
//                        MySnackbar snackbar = MySnackbar.getInstance(LoginActivity.this);
//                        snackbar.show(json.getString("Please try again"));
                        Preference preference = Preference.getInstance(LoginActivity.this);
                        preference.putString("student_id", "");
                        Toast.makeText(LoginActivity.this,"Please try again",Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Preference preference = Preference.getInstance(LoginActivity.this);
                    preference.putString("student_id", "");
                    Toast.makeText(LoginActivity.this,"Please try again",Toast.LENGTH_LONG).show();
                }


            }
        });
    }


}
