package cpm.com.gskmtorange.password;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Trace;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

//import com.crashlytics.android.Crashlytics;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import cpm.com.gskmtorange.LoginActivity;
import cpm.com.gskmtorange.MainActivity;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.SelectLanguageActivity;
import cpm.com.gskmtorange.autoupdate.AutoUpdateActivity;
import cpm.com.gskmtorange.blurlockview.BlurLockView;
import cpm.com.gskmtorange.blurlockview.Directions.HideType;
import cpm.com.gskmtorange.blurlockview.Directions.ShowType;
import cpm.com.gskmtorange.blurlockview.Eases.EaseType;
import cpm.com.gskmtorange.blurlockview.Password;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.xmlGetterSetter.FailureGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.LoginGetterSetter;
import cpm.com.gskmtorange.xmlHandlers.XMLHandlers;

public class MPinActivity extends AppCompatActivity implements
        View.OnClickListener,
        BlurLockView.OnPasswordInputListener,
        BlurLockView.OnLeftButtonClickListener,GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    BlurLockView blurLockView;
    ImageView imageView1;
    String pin = "";
    boolean IS_PASSWORD_CHECK;

    private SharedPreferences preferences = null;
    private SharedPreferences.Editor editor = null;

    private Dialog dialog;
    
    String userId, password, app_ver;
    int eventType;
    LoginGetterSetter lgs = null;
    FirebaseAnalytics mFirebaseAnalytics;
    static int counter = 1;
  //  Trace myTrace;
    private int versionCode;

    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 10;
    private static final int MY_PERMISSIONS_REQUEST_LOCATION = 11;
    private static final int MY_PERMISSIONS_REQUEST_STORAGE_READ = 12;
    private static final int MY_PERMISSIONS_REQUEST_STORAGE_WRITE = 14;

    GoogleApiClient mGoogleApiClient;
    private static int UPDATE_INTERVAL = 200; // 5 sec
    private static int FATEST_INTERVAL = 100; // 1 sec
    private static int DISPLACEMENT = 1; // 10 meters
    private static final int REQUEST_LOCATION = 1;
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
    private Location mLastLocation;
    private LocationRequest mLocationRequest;
    private Context context;

    double lat = 0.0;
    double lon = 0.0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_mpin);

        context = this;
        /*Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);*/

        // Obtain the FirebaseAnalytics instance.
      //  mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
      //  myTrace = FirebasePerformance.getInstance().newTrace("test_trace");
       // myTrace.start();

        IS_PASSWORD_CHECK = getIntent().getBooleanExtra(CommonString.IS_PASSWORD_CHECK, false);

        imageView1 = (ImageView) findViewById(R.id.image_1);

        blurLockView = (BlurLockView) findViewById(R.id.blurlockview);

        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        editor = preferences.edit();

        try {
            app_ver = String.valueOf(getPackageManager().getPackageInfo(getPackageName(), 0).versionName);

            // login_version.setText("Parinaam Version " + app_ver);
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Set the view that need to be blurred
        blurLockView.setBlurredView(imageView1);

        // Set the password
        if (IS_PASSWORD_CHECK) {
            //preferences = PreferenceManager.getDefaultSharedPreferences(this);
            String mpin = preferences.getString(CommonString.MPIN, null);
            blurLockView.setCorrectPassword(mpin);
            blurLockView.setLeftButton(getString(R.string.forget_mpin));
            blurLockView.setTitle(getString(R.string.pls_enter_four_digit_mpin));
        } else {
            blurLockView.setCorrectPassword("abcd");
            blurLockView.setLeftButton(getString(R.string.set_mpin));
            blurLockView.setTitle(getString(R.string.pls_set_four_digit_mpin));
        }

        blurLockView.setIs_Password_Check_Mode(IS_PASSWORD_CHECK);



        blurLockView.setRightButton(getString(R.string.clear));
        blurLockView.setTypeface(getTypeface());
        blurLockView.setOnLeftButtonClickListener(this);
        blurLockView.setOnPasswordInputListener(this);

        //blurLockView.setType(getPasswordType(), false);
        //blurLockView.setPasswordLength(4);

       /* blurLockView.show(
                getIntent().getIntExtra("SHOW_DURATION", 1000),
                getShowType(getIntent().getIntExtra("SHOW_DIRECTION", 0)),
                getEaseType(getIntent().getIntExtra("SHOW_EASE_TYPE", 30)));*/
        blurLockView.setType(Password.NUMBER, true);

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

        checkAppPermission(Manifest.permission.CAMERA, MY_PERMISSIONS_REQUEST_CAMERA);
    }

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

        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();

        }
        checkgpsEnableDevice();
    }

    private Password getPasswordType() {
        if ("PASSWORD_NUMBER".equals(getIntent().getStringExtra("PASSWORD_TYPE")))
            return Password.NUMBER;
        else if ("PASSWORD_NUMBER".equals(getIntent().getStringExtra("PASSWORD_TYPE")))
            return Password.TEXT;
        return Password.NUMBER;
    }

    private Typeface getTypeface() {
        if ("SAN".equals(getIntent().getStringExtra("TYPEFACE")))
            return Typeface.createFromAsset(getAssets(), "fonts/San Francisco Regular.ttf");
        else if ("DEFAULT".equals(getIntent().getStringExtra("TYPEFACE")))
            return Typeface.DEFAULT;
        return Typeface.DEFAULT;
    }

    @Override
    public void correct(String inputPassword) {

        if (IS_PASSWORD_CHECK) {
            userId = preferences.getString(CommonString.KEY_USERNAME, "");
            password = preferences.getString(CommonString.KEY_PASSWORD, "");

            new AuthenticateTask().execute();
        } else {
            Toast.makeText(this,
                    "Correct",
                    Toast.LENGTH_SHORT).show();
        }


       /* blurLockView.hide(
                getIntent().getIntExtra("HIDE_DURATION", 1000),
                getHideType(getIntent().getIntExtra("HIDE_DIRECTION", 0)),
                getEaseType(getIntent().getIntExtra("HIDE_EASE_TYPE", 30)));*/
    }

    @Override
    public void incorrect(String inputPassword) {

        if (IS_PASSWORD_CHECK) {

            int incorrect_times = blurLockView.getIncorrectInputTimes();
            if (++incorrect_times >= 3) {
                /*Toast.makeText(this,
                        R.string.error_incorrect_password,
                        Toast.LENGTH_SHORT).show();*/

                Snackbar snackbar = Snackbar.make(blurLockView, R.string.incorrect_mpin_limit_reached, Snackbar.LENGTH_INDEFINITE);
                View view = snackbar.getView();
                /*TextView tv = (TextView)view.findViewById(android.support.design.R.id.snackbar_text);
                tv.setTextColor(Color.RED);*/
                snackbar.setAction(R.string.reset, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        editor.putString(CommonString.MPIN, null);

                        editor.commit();

                        finish();
                        Intent in = new Intent(getApplicationContext(), LoginActivity.class);
                        startActivity(in);

                    }
                });
                snackbar.setActionTextColor(Color.GREEN);
                snackbar.show();
            } else {

                int count = 3 - incorrect_times;
                String attemt_str;
                if (count == 1) {
                    attemt_str = ". Attempt left - " + count;
                } else {
                    attemt_str = ". Attempts left - " + count;
                }

                String msg = getString(R.string.error_incorrect_pin) + attemt_str;
                //blurLockView.setIncorrectInputTimes(incorrect_times);
                Toast.makeText(this,
                        msg,
                        Toast.LENGTH_SHORT).show();
            }

        } else {
            pin = inputPassword;
        }

    }

    @Override
    public void input(String inputPassword) {
        pin = inputPassword;
    }

    @Override
    public void clear(String remainingPassword) {
        pin = remainingPassword;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_1:
               /* blurLockView.show(
                        getIntent().getIntExtra("SHOW_DURATION", 1000),
                        getShowType(getIntent().getIntExtra("SHOW_DIRECTION", 0)),
                        getEaseType(getIntent().getIntExtra("SHOW_EASE_TYPE", 30)));
                blurLockView.setType(Password.TEXT, true);*/
                break;
        }
    }

    @Override
    public void onClick() {

        if (IS_PASSWORD_CHECK) {

            Snackbar snackbar = Snackbar.make(blurLockView, R.string.need_to_reset_mpin, Snackbar.LENGTH_INDEFINITE);
            View view = snackbar.getView();
                /*TextView tv = (TextView)view.findViewById(android.support.design.R.id.snackbar_text);
                tv.setTextColor(Color.RED);*/
            snackbar.setAction(R.string.reset, new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    editor.putString(CommonString.MPIN, null);

                    editor.commit();

                    finish();
                    Intent in = new Intent(getApplicationContext(), LoginActivity.class);
                    startActivity(in);

                }
            });
            snackbar.setActionTextColor(Color.GREEN);
            snackbar.show();
        } else {
            if (pin.length() == 4) {

                editor.putString(CommonString.MPIN, pin);

                editor.commit();

                Intent in = new Intent(getApplicationContext(), MainActivity.class);
                //Intent in = new Intent(getApplicationContext(), OneQADActivity.class);

                startActivity(in);

                finish();
            } else {
                Toast.makeText(getApplicationContext(), "Please fill four digit MPin", Toast.LENGTH_SHORT).show();
            }
        }

    }


    private int downsamepleFactor;

    private ShowType getShowType(int p) {
        ShowType showType = ShowType.FROM_TOP_TO_BOTTOM;
        switch (p) {
            case 0:
                showType = ShowType.FROM_TOP_TO_BOTTOM;
                break;
            case 1:
                showType = ShowType.FROM_RIGHT_TO_LEFT;
                break;
            case 2:
                showType = ShowType.FROM_BOTTOM_TO_TOP;
                break;
            case 3:
                showType = ShowType.FROM_LEFT_TO_RIGHT;
                break;
            case 4:
                showType = ShowType.FADE_IN;
                break;
        }
        return showType;
    }

    private HideType getHideType(int p) {
        HideType hideType = HideType.FROM_TOP_TO_BOTTOM;
        switch (p) {
            case 0:
                hideType = HideType.FROM_TOP_TO_BOTTOM;
                break;
            case 1:
                hideType = HideType.FROM_RIGHT_TO_LEFT;
                break;
            case 2:
                hideType = HideType.FROM_BOTTOM_TO_TOP;
                break;
            case 3:
                hideType = HideType.FROM_LEFT_TO_RIGHT;
                break;
            case 4:
                hideType = HideType.FADE_OUT;
                break;
        }
        return hideType;
    }

    private EaseType getEaseType(int p) {
        EaseType easeType = EaseType.Linear;
        switch (p) {
            case 0:
                easeType = EaseType.EaseInSine;
                break;
            case 1:
                easeType = EaseType.EaseOutSine;
                break;
            case 2:
                easeType = EaseType.EaseInOutSine;
                break;
            case 3:
                easeType = EaseType.EaseInQuad;
                break;
            case 4:
                easeType = EaseType.EaseOutQuad;
                break;
            case 5:
                easeType = EaseType.EaseInOutQuad;
                break;
            case 6:
                easeType = EaseType.EaseInCubic;
                break;
            case 7:
                easeType = EaseType.EaseOutCubic;
                break;
            case 8:
                easeType = EaseType.EaseInOutCubic;
                break;
            case 9:
                easeType = EaseType.EaseInQuart;
                break;
            case 10:
                easeType = EaseType.EaseOutQuart;
                break;
            case 11:
                easeType = EaseType.EaseInOutQuart;
                break;
            case 12:
                easeType = EaseType.EaseInQuint;
                break;
            case 13:
                easeType = EaseType.EaseOutQuint;
                break;
            case 14:
                easeType = EaseType.EaseInOutQuint;
                break;
            case 15:
                easeType = EaseType.EaseInExpo;
                break;
            case 16:
                easeType = EaseType.EaseOutExpo;
                break;
            case 17:
                easeType = EaseType.EaseInOutExpo;
                break;
            case 18:
                easeType = EaseType.EaseInCirc;
                break;
            case 19:
                easeType = EaseType.EaseOutCirc;
                break;
            case 20:
                easeType = EaseType.EaseInOutCirc;
                break;
            case 21:
                easeType = EaseType.EaseInBack;
                break;
            case 22:
                easeType = EaseType.EaseOutBack;
                break;
            case 23:
                easeType = EaseType.EaseInOutBack;
                break;
            case 24:
                easeType = EaseType.EaseInElastic;
                break;
            case 25:
                easeType = EaseType.EaseOutElastic;
                break;
            case 26:
                easeType = EaseType.EaseInOutElastic;
                break;
            case 27:
                easeType = EaseType.EaseInBounce;
                break;
            case 28:
                easeType = EaseType.EaseOutBounce;
                break;
            case 29:
                easeType = EaseType.EaseInOutBounce;
                break;
            case 30:
                easeType = EaseType.Linear;
                break;
        }
        return easeType;
    }

    /*public void showComment(){

        dialog = new Dialog(MPinActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog.setContentView(R.layout.comment_layout);
        TextView tv = (TextView) dialog.findViewById(R.id.tv_comment);

        tv.setText("");

        Window window = dialog.getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();

        wlp.gravity = Gravity.TOP;
        //wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
        window.setAttributes(wlp);

        dialog.show();

    }*/

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */

    private class AuthenticateTask extends AsyncTask<Void, Void, String> {
        private Dialog dialog;

        @Override
        protected void onPreExecute() {

            super.onPreExecute();

            dialog = new Dialog(MPinActivity.this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            dialog.setContentView(R.layout.progress_layout);

            Window window = dialog.getWindow();
            WindowManager.LayoutParams wlp = window.getAttributes();

            wlp.gravity = Gravity.CENTER;
            //wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
            window.setAttributes(wlp);

            dialog.setCancelable(false);

            if (!dialog.isShowing()) {
                dialog.show();
            }
        }

        @Override
        protected String doInBackground(Void... params) {

            try {

                versionCode = getPackageManager().getPackageInfo(
                        getPackageName(), 0).versionCode;
                
                String userauth_xml = "[DATA]" + "[USER_DATA][USER_ID]"
                        + userId + "[/USER_ID]" + "[PASSWORD]" + password
                        + "[/PASSWORD]" + "[IN_TIME]" + CommonFunctions.getCurrentTimeWithLanguage(getApplicationContext())
                        + "[/IN_TIME]" + "[LATITUDE]" + lat
                        + "[/LATITUDE]" + "[LONGITUDE]" + lon
                        + "[/LONGITUDE]" + "[APP_VERSION]" + app_ver
                        + "[/APP_VERSION]" + "[ATT_MODE]OnLine[/ATT_MODE]"
                        + "[NETWORK_STATUS]" + "LoginStatus"
                        + "[/NETWORK_STATUS]" + "[/USER_DATA][/DATA]";

                SoapObject request = new SoapObject(CommonString.NAMESPACE,
                        CommonString.METHOD_LOGIN);
                request.addProperty("onXML", userauth_xml);

                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);
                envelope.dotNet = true;
                envelope.setOutputSoapObject(request);

                HttpTransportSE androidHttpTransport = new HttpTransportSE(
                        CommonString.URL);

                androidHttpTransport.call(CommonString.SOAP_ACTION_LOGIN,
                        envelope);

                Object result = (Object) envelope.getResponse();

                if (result.toString()
                        .equalsIgnoreCase(CommonString.KEY_FAILURE)) {

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {

                            showAlert(CommonString.MESSAGE_FAILURE);
                        }
                    });

                } else if (result.toString().equalsIgnoreCase(
                        CommonString.KEY_FALSE)) {

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {

                            showAlert(CommonString.MESSAGE_FALSE);
                        }
                    });

                } else if (result.toString().equalsIgnoreCase(
                        CommonString.KEY_CHANGED)) {

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {

                            showAlert(CommonString.MESSAGE_CHANGED);
                        }
                    });

                } else {

                    XmlPullParserFactory factory = XmlPullParserFactory
                            .newInstance();
                    factory.setNamespaceAware(true);
                    XmlPullParser xpp = factory.newPullParser();

                    xpp.setInput(new StringReader(result.toString()));
                    xpp.next();
                    eventType = xpp.getEventType();
                    final FailureGetterSetter failureGetterSetter = XMLHandlers
                            .failureXMLHandler(xpp, eventType);

                    if (failureGetterSetter.getStatus().equalsIgnoreCase(
                            CommonString.KEY_FAILURE)) {
                       /* final AlertMessage message = new AlertMessage(
                                MPinActivity.this, CommonString.METHOD_LOGIN
                                + failureGetterSetter.getErrorMsg(),
                                "login", null);*/
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                showAlert(CommonString.METHOD_LOGIN
                                        + failureGetterSetter.getErrorMsg());
                            }
                        });
                    } else {

                        try {
                            // For String source

                            xpp.setInput(new StringReader(result.toString()));
                            xpp.next();
                            eventType = xpp.getEventType();
                            lgs = XMLHandlers.loginXMLHandler(xpp, eventType);

                        } catch (XmlPullParserException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        // PUT IN PREFERENCES
                        editor.putString(CommonString.KEY_USERNAME, userId);
                        editor.putString(CommonString.KEY_PASSWORD, password);
                        editor.putString(CommonString.KEY_VERSION, lgs.getAPP_VERSION());

                        editor.putString(CommonString.KEY_PATH, lgs.getAPP_PATH());

                        editor.putString(CommonString.KEY_DATE, lgs.getCURRENTDATE());
                        //editor.putString(CommonString.KEY_DATE, "01/25/2019");
                        editor.putString(CommonString.KEY_COUNTRY_ID, lgs.getCOUNTRY_ID());

                        editor.commit();

                        setDataFromSharedPreferences(lgs);

                        Bundle bundle = new Bundle();
                        bundle.putString(FirebaseAnalytics.Param.ITEM_ID, userId);
                        bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, CommonString.KEY_LOGIN_DATA);
                        bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "Data");
                        bundle.putString(CommonString.KEY_LANGUAGE, preferences.getString(CommonString.KEY_LANGUAGE, ""));
                      //  mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

                       // Crashlytics.setUserIdentifier(userId);

                        return CommonString.KEY_SUCCESS;

                    }
                }

                return "";

            } catch (MalformedURLException e) {

            /*    final AlertMessage message = new AlertMessage(
                        MPinActivity.this, AlertMessage.MESSAGE_EXCEPTION,
                        "acra_login", e);*/

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {

                        showAlert(CommonString.MESSAGE_EXCEPTION);
                    }
                });

            } catch (IOException e) {
               /* final AlertMessage message = new AlertMessage(
                        MPinActivity.this,
                        AlertMessage.MESSAGE_SOCKETEXCEPTION, "socket_login", e);*/

                counter++;
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if (counter < 3) {
                            new AuthenticateTask().execute();
                        } else {
                            showAlert(getString(R.string.nonetwork));
                            counter = 1;
                        }
                    }
                });
            } catch (Exception e) {
              /*  final AlertMessage message = new AlertMessage(
                        MPinActivity.this, AlertMessage.MESSAGE_EXCEPTION,
                        "acra_login", e);*/
                //Crashlytics.log(7, CommonString.MESSAGE_EXCEPTION, e.toString());
                //Crashlytics.logException(e.getCause());
               // Crashlytics.logException(new Exception("My custom login Exception"));
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        showAlert(CommonString.MESSAGE_EXCEPTION);
                    }
                });
            }
            return "";

        }

        @Override
        protected void onPostExecute(String result) {

            super.onPostExecute(result);

            //Stop performance trace
        //    myTrace.stop();

            if (result.equals(CommonString.KEY_SUCCESS)) {

                //set true for South Africa
                boolean forSA = false;

                if(forSA){
                    //For SA Only
                    if (preferences.getString(CommonString.KEY_LANGUAGE, "").equals("")) {

                        Intent intent = new Intent(getBaseContext(),
                                SelectLanguageActivity.class);

                        intent.putExtra(CommonString.KEY_LOGIN_DATA, lgs);
                        startActivity(intent);

                        finish();
                    } else {

                        setLanguageDataFromSharedPreferences();

                        CommonFunctions.updateLangResources(getApplicationContext(), preferences.getString(CommonString.KEY_LANGUAGE, ""));

                        Intent intent = new Intent(getBaseContext(),
                                MainActivity.class);
                        startActivity(intent);

                        finish();

                        //uploadPreviousImages();
                    }
                }
                else {
                    //for other than SA
                    //database.open();
                    if (preferences.getString(CommonString.KEY_VERSION, "").equals(
                            Integer.toString(versionCode))) {

                        setLanguageDataFromSharedPreferences();

                        Intent in = new Intent(getApplicationContext(), MainActivity.class);
                        in.putExtra(CommonString.IS_PASSWORD_CHECK, false);
                        startActivity(in);
                        finish();


                    } else {

                        Intent intent = new Intent(getBaseContext(),
                                AutoUpdateActivity.class);

                        intent.putExtra(CommonString.KEY_PATH,
                                preferences.getString(CommonString.KEY_PATH, ""));
                        startActivity(intent);
                        finish();
                    }
                }

            }
            dialog.dismiss();
        }

    }

    ArrayList<String> language, culture_id, notice_url;

    LoginGetterSetter login_data;

    private void setLanguageDataFromSharedPreferences(){
        Gson gson = new Gson();
        login_data = new LoginGetterSetter();

        String jsonPreferences = preferences.getString(CommonString.KEY_LOOGIN_PREF, "");

        Type type = new TypeToken<LoginGetterSetter>() {}.getType();
        login_data = gson.fromJson(jsonPreferences, type);

        language = login_data.getCULTURE_NAME();
        culture_id = login_data.getCULTURE_ID();
        notice_url = login_data.getNOTICE_URL();

        String lang = preferences.getString(CommonString.KEY_LANGUAGE, "");

        if(language.size()>0){
            for(int i=0; i<language.size();i++){
                if(lang.equals(language.get(i))){
                    editor.putString(CommonString.KEY_LANGUAGE, language.get(i));
                    editor.putString(CommonString.KEY_CULTURE_ID, culture_id.get(i));
                    editor.putString(CommonString.KEY_NOTICE_BOARD_LINK, notice_url.get(i));
                    editor.commit();
                    break;
                }
            }
        }

        //return ;
    }

    public void showAlert(String str) {

        AlertDialog.Builder builder = new AlertDialog.Builder(MPinActivity.this);
        builder.setTitle("Parinaam");
        builder.setMessage(str).setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                       /* Intent i = new Intent(activity, StorelistActivity.class);
                        activity.startActivity(i);
                        activity.finish();*/
                        finish();

                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    /*public String getCurrentTimeNotUsed() {

        Calendar m_cal = Calendar.getInstance();

        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        String intime = formatter.format(m_cal.getTime());

        return intime;
    }*/

    private static String arabicToenglish(String number) {
        char[] chars = new char[number.length()];
        for (int i = 0; i < number.length(); i++) {
            char ch = number.charAt(i);
            if (ch >= 0x0660 && ch <= 0x0669)
                ch -= 0x0660 - '0';
            else if (ch >= 0x06f0 && ch <= 0x06F9)
                ch -= 0x06f0 - '0';
            chars[i] = ch;
        }
        return new String(chars);
    }

    private void setDataFromSharedPreferences(LoginGetterSetter lgs) {
        Gson gson = new Gson();
        String jsonCurProduct = gson.toJson(lgs);

        //SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(CommonString.KEY_LOOGIN_PREF, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putString(CommonString.KEY_LOOGIN_PREF, jsonCurProduct);
        editor.commit();
    }
    
    //permission and location related
    void checkAppPermission(String permission, int requestCode) {

        boolean permission_flag = false;
        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(MPinActivity.this,
                permission)
                != PackageManager.PERMISSION_GRANTED) {

            // Permission is not granted
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(MPinActivity.this,
                    permission)) {
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                showOnPermissiondenied(Manifest.permission.CAMERA, MY_PERMISSIONS_REQUEST_CAMERA, 1);
            } else {
                // No explanation needed; request the permission
                ActivityCompat.requestPermissions(MPinActivity.this,
                        new String[]{permission},
                        requestCode);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        } else {
            // Permission has already been granted
            if (requestCode == MY_PERMISSIONS_REQUEST_CAMERA) {
                checkAppPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, MY_PERMISSIONS_REQUEST_STORAGE_WRITE);
            } else if (requestCode == MY_PERMISSIONS_REQUEST_STORAGE_WRITE) {
                checkAppPermission(Manifest.permission.READ_EXTERNAL_STORAGE, MY_PERMISSIONS_REQUEST_STORAGE_READ);
            } else if (requestCode == MY_PERMISSIONS_REQUEST_STORAGE_READ) {
                checkAppPermission(Manifest.permission.ACCESS_FINE_LOCATION, MY_PERMISSIONS_REQUEST_LOCATION);
            } else {

                // Create a Folder for Images

                File file = new File(Environment.getExternalStorageDirectory(), ".GSK_MT_ORANGE_IMAGES");
                if (!file.isDirectory()) {
                    file.mkdir();
                }
                File file_planogram = new File(Environment.getExternalStorageDirectory(), "GSK_MT_ORANGE_Planogram_Images");
                if (!file_planogram.isDirectory()) {
                    file_planogram.mkdir();
                }

                if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(getApplicationContext(),
                        android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                        ContextCompat.checkSelfPermission(getApplicationContext(),
                                android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }

                if (checkPlayServices()) {
                    // Building the GoogleApi client
                    buildGoogleApiClient();

                    createLocationRequest();
                }

                // Create an instance of GoogleAPIClient.
                if (mGoogleApiClient == null) {
                    mGoogleApiClient = new GoogleApiClient.Builder(this)
                            .addConnectionCallbacks(this)
                            .addOnConnectionFailedListener(this)
                            .addApi(LocationServices.API)
                            .build();
                }

                //attemptLogin();
            }

        }
    }

    void showOnPermissiondenied(final String permissionsRequired, final int request_code, final int check) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MPinActivity.this);
        builder.setTitle("Need Multiple Permissions");
        builder.setMessage("This app needs Camera, Storage and Location permissions.");
        builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                if (check == 0) {
                    checkAppPermission(permissionsRequired, request_code);
                } else {
                    ActivityCompat.requestPermissions(MPinActivity.this,
                            new String[]{permissionsRequired},
                            request_code);
                }

            }
        });
       /* builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                finish();
            }
        });*/
        builder.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        checkAppPermission(Manifest.permission.CAMERA, MY_PERMISSIONS_REQUEST_CAMERA);

        /*if (requestCode == PERMISSIONS_REQUEST_READ_PHONE_STATE
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            imeiNumbers = imei.getDeviceImei();
        }

        */

        if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(getApplicationContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(getApplicationContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        if (checkPlayServices()) {
            // Building the GoogleApi client
            buildGoogleApiClient();

            createLocationRequest();
        }

        // Create an instance of GoogleAPIClient.
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }

    }

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.notsuppoted)
                        , Toast.LENGTH_LONG)
                        .show();
                finish();
            }
            return false;
        }
        return true;
    }

    protected synchronized void buildGoogleApiClient() {
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(context)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    @Override
    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

        // Toast.makeText(this,  " WORKS_lat_lon " + latLng, Toast.LENGTH_LONG).show();
        //  updateLocation(latLng);
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }

    }

    @SuppressLint("MissingPermission")
    protected void startLocationUpdates() {

        if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (mGoogleApiClient != null) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
                // Toast.makeText(getApplicationContext(), "startLocation - Lat" + lat + "Long" + lon, Toast.LENGTH_LONG).show();
            }
        }

    }

    public static int distFrom(double lat1, double lng1, double lat2, double lng2) {
        double earthRadius = 6371000; //meters
        double dLat = Math.toRadians(lat2 - lat1);
        double dLng = Math.toRadians(lng2 - lng1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                        Math.sin(dLng / 2) * Math.sin(dLng / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        int dist = (int) (earthRadius * c);

        return dist;
    }

    @Override
    public void onConnected(Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (mLastLocation != null) {
                lat = mLastLocation.getLatitude();
                lon = mLastLocation.getLongitude();
                //  Toast.makeText(getApplicationContext(), "onconnected lat-" + lat + " Long-" + lon, Toast.LENGTH_SHORT).show();
            }
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    private boolean checkgpsEnableDevice() {
        boolean flag = true;
        if (!hasGPSDevice(context)) {
            Toast.makeText(context, "Gps not Supported", Toast.LENGTH_SHORT).show();
        }
        final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(context)) {
            enableLoc();
            flag = false;
        } else if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(context)) {
            flag = true;
        }
        return flag;
    }

    private boolean hasGPSDevice(Context context) {
        final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (mgr == null)
            return false;
        final List<String> providers = mgr.getAllProviders();
        if (providers == null)
            return false;
        return providers.contains(LocationManager.GPS_PROVIDER);
    }

    private void enableLoc() {
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
        builder.setAlwaysShow(true);
        if (mGoogleApiClient != null) {
            PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
            result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                @Override
                public void onResult(LocationSettingsResult result) {
                    final Status status = result.getStatus();
                    switch (status.getStatusCode()) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            try {
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                status.startResolutionForResult((Activity) context, REQUEST_LOCATION);
                            } catch (IntentSender.SendIntentException e) {
                                // Ignore the error.
                            }
                            break;
                    }
                }
            });
        }
    }
}
