package com.cpm.lorealbaautomation.pinviewactivity;

import static com.cpm.lorealbaautomation.constant.CommonFunctions.hideKeyboard;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
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.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.goodiebag.pinview.Pinview;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
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.SettingsClient;
import com.google.gson.Gson;
import com.cpm.lorealbaautomation.AutoUpdateActivity;
import com.cpm.lorealbaautomation.BuildConfig;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.DealarBoardActivity;
import com.cpm.lorealbaautomation.Get_IMEI_number.ImeiNumberClass;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.UserLoginActivity;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gettersetter.LoginGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.BADeviceLoginGetterSetter;
import com.cpm.lorealbaautomation.password.ChangePasswordActivity;
import com.cpm.lorealbaautomation.retrofit.PostApi;
import com.cpm.lorealbaautomation.timer.TimerActivity;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class
PinViewActivity extends AppCompatActivity implements View.OnClickListener {
    private String counterId = "";
    private final String visitdate = "";
    private String Update_Visit_Date;
    private String userType;
    Pinview pinview_confirm, pinview_start;
    TextView btn_clear, btn_forgot_pin;
    Button btn_done;

    ArrayList<LoginGetterSetter> allLoginData = new ArrayList<>();
    private String user_id, visit_date;
    private SharedPreferences.Editor editor = null;
    SharedPreferences preferences;
    private Lorealba_Database db;
    boolean IS_PASSWORD_CHECK;
    Toolbar toolbar;
    Context context;

    LoginGetterSetter loginGetterSetter;
    private int versionCode;
    ProgressDialog loading;
    private String[] imeiNumbers;
    private double lat = 0.0;
    private double lon = 0.0;
    private static int UPDATE_INTERVAL = 200; // 5 sec
    private static int FATEST_INTERVAL = 100;
    private static final int PERMISSIONS_REQUEST_READ_PHONE_STATE = 999;// 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 ImeiNumberClass imei;
    private static final int PERMISSION_ALL = 99;
    private String app_ver;
    private String manufacturer;
    private String model;
    private String os_version;
    TextView txt_set_pin, txt_confirm_pin;
    CardView card_set_pin_layout, card_confirm_pin_layout;
    private FusedLocationProviderClient fusedLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pin_view);
        context = this;
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        db = new Lorealba_Database(context);
        db.open();
        getId();
        check_keyboard();
        checkAndRequestPermissions();
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_PHONE_STATE},
                    PERMISSIONS_REQUEST_READ_PHONE_STATE);
        } else {
            imeiNumbers = imei.getDeviceImei();
        }
        getDeviceName();
        getLastLocation();
    }

    private boolean checkAndRequestPermissions() {
        int CAMERA = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
        int ACCESS_NETWORK_STATE = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_NETWORK_STATE);
        int ACCESS_COARSE_LOCATION = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
        int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        int READ_PHONE_STATE = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
        List<String> listPermissionsNeeded = new ArrayList<>();

        if (CAMERA != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.CAMERA);
        }

        if (ACCESS_NETWORK_STATE != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_NETWORK_STATE);
        }
        if (ACCESS_COARSE_LOCATION != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        if (locationPermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        if (READ_PHONE_STATE != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
        }


        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), PERMISSION_ALL);
            return false;
        }
        return true;
    }

    private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(this).setMessage(message).setPositiveButton("OK", okListener).setNegativeButton("Cancel", okListener).create().show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //test("", "Permission callback called-------");
        if (requestCode == PERMISSION_ALL) {
            Map<String, Integer> perms = new HashMap<>();
            // Initialize the map with both permissions
            perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.ACCESS_NETWORK_STATE, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
            // Fill with actual results from user
            if (grantResults.length > 0) {
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                // Check for both permissions

                boolean allPermissionsGranted =
                        Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.CAMERA)) &&
                                Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_NETWORK_STATE)) &&
                                Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_COARSE_LOCATION)) &&
                                Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_FINE_LOCATION)) &&
                                Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.READ_PHONE_STATE));

                if (allPermissionsGranted) {
                    //test("Permissions", "All required permissions granted");
                    createLocationRequest();
                    fusedLocationClient = LocationServices.getFusedLocationProviderClient((Activity) context);
                    getLastLocation();
                    getDeviceName();
                    imeiNumbers = imei.getDeviceImei();
                } else {
                    //test("", "Some permissions are not granted ask again ");
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NETWORK_STATE) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) {
                        showDialogOK("Location,File,Call and Camera Services Permission required for this app",
                                (dialog, which) -> {
                                    if (which == DialogInterface.BUTTON_POSITIVE) {
                                        checkAndRequestPermissions();
                                    } else if (which == DialogInterface.BUTTON_NEGATIVE) {// proceed with logic by disabling the related features or quit the app.
                                        Intent startMain = new Intent(Intent.ACTION_MAIN);
                                        startMain.addCategory(Intent.CATEGORY_HOME);
                                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(startMain);
                                    }
                                });
                    } else {
                        Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    }

    private void getLastLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // Request location permissions
            return;
        }
        try {
            fusedLocationClient.getLastLocation()
                    .addOnSuccessListener(this, location -> {
                        if (location != null) {
                            lat = location.getLatitude();
                            lon = location.getLongitude();
                            //test("Location", "Lat: " + lat + ", Lng: " + lon);
                        }
                    });
        } catch (Exception e) {
            e.fillInStackTrace(); //test("Location", "Lat: " + lat + ", Lng: " + lon);}
        }
    }

    @SuppressLint("SetTextI18n")
    private void getId() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }
        pinview_confirm = (Pinview) findViewById(R.id.pinview_confirm);
        pinview_start = (Pinview) findViewById(R.id.pinview_start);
        btn_clear = (TextView) findViewById(R.id.btn_clear);
        btn_forgot_pin = (TextView) findViewById(R.id.btn_forgot_pin);
        btn_done = (Button) findViewById(R.id.btn_done);

        txt_set_pin = (TextView) findViewById(R.id.txt_set_pin);
        txt_confirm_pin = (TextView) findViewById(R.id.txt_confirm_pin);
        card_set_pin_layout = (CardView) findViewById(R.id.card_set_pin_layout);
        card_confirm_pin_layout = (CardView) findViewById(R.id.card_confirm_pin_layout);

        btn_clear.setOnClickListener(this);
        btn_done.setOnClickListener(this);
        btn_forgot_pin.setOnClickListener(this);
        preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        counterId = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        userType = preferences.getString(CommonString.KEY_USER_TYPE, "");
        IS_PASSWORD_CHECK = getIntent().getBooleanExtra(CommonString.IS_PASSWORD_CHECK, false);
        if (getIntent().getSerializableExtra(CommonString.KEY_USERNAME) != null) {
            user_id = getIntent().getStringExtra(CommonString.KEY_USERNAME);
        }
        if (getIntent().getSerializableExtra(CommonString.KEY_Update_Visit_Date) != null) {
            Update_Visit_Date = getIntent().getStringExtra(CommonString.KEY_Update_Visit_Date);
        }
        setTitle("PinView - " + user_id);
        imei = new ImeiNumberClass(context);
        imeiNumbers = imei.getDeviceImei();
        getDeviceName();
        try {
            app_ver = String.valueOf(getPackageManager().getPackageInfo(getPackageName(), 0).versionName);

        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.fillInStackTrace();
        }

        db.open();
        allLoginData = db.getlistAllData(visit_date, user_id);

        if (IS_PASSWORD_CHECK) {
            btn_done.setText("Submit");
            txt_set_pin.setText("Enter PIN");
            pinview_confirm.requestFocus();
            card_confirm_pin_layout.setVisibility(View.VISIBLE);
            card_set_pin_layout.setVisibility(View.GONE);
            txt_confirm_pin.setVisibility(View.INVISIBLE);
            btn_forgot_pin.setVisibility(View.VISIBLE);
        } else {
            pinview_start.requestFocus();
            btn_done.setText("Set PIN");
            txt_set_pin.setText("Set PIN");
            card_confirm_pin_layout.setEnabled(false);
            card_confirm_pin_layout.setVisibility(View.VISIBLE);
            card_set_pin_layout.setVisibility(View.VISIBLE);
            btn_forgot_pin.setVisibility(View.GONE);
            txt_confirm_pin.setVisibility(View.VISIBLE);
        }

        pinview_start.setPinViewEventListener((pinview, fromUser) -> {
            if (!IS_PASSWORD_CHECK) {
                if (!pinview.getValue().isEmpty()) {
                    if (!pinview.getValue().isEmpty() && pinview.getValue().length() != 4) {
                        card_confirm_pin_layout.setEnabled(false);
                    } else {
                        pinview_confirm.requestFocus();
                        card_confirm_pin_layout.setEnabled(true);
                    }
                } else {
                    card_confirm_pin_layout.setEnabled(false);
                }
            }

        });

        pinview_confirm.setPinViewEventListener((pinview, fromUser) -> {
            //Make api calls here or what not
            if (!IS_PASSWORD_CHECK) {
                if (pinview_start.getValue().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Set First MPIN");
                    pinview_confirm.clearValue();
                }
            }
        });

        pinview_start.setTextColor(Color.BLACK);
        pinview_start.showCursor(true);
        pinview_confirm.setTextColor(Color.BLACK);
        pinview_confirm.showCursor(true);
    }

    public void getDeviceName() {
        manufacturer = Build.MANUFACTURER;
        model = Build.MODEL;
        os_version = Build.VERSION.RELEASE;
    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_done) {
            hideKeyboard(this);
            if (!IS_PASSWORD_CHECK && pinview_start.getValue().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Set MPIN");
            } else if (!IS_PASSWORD_CHECK && pinview_start.getValue().length() != 4) {
                AlertandMessages.showToastMsg(context, "Please Set 4 Digit MPin");
            } else if (pinview_confirm.getValue().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Set Confirm MPIN");
            } else if (pinview_confirm.getValue().length() != 4) {
                AlertandMessages.showToastMsg(context, "Please Set 4 Digit Confirm MPIN");
            } else if (!IS_PASSWORD_CHECK && !pinview_start.getValue().equals(pinview_confirm.getValue())) {
                AlertandMessages.showToastMsg(context, "MPIN Does Not Match");
                pinview_confirm.clearValue();
            } else if (!allLoginData.isEmpty() && allLoginData.get(0).getMpin() != null && !pinview_confirm.getValue().equalsIgnoreCase(allLoginData.get(0).getMpin())) {
                AlertandMessages.showToastMsg(context, "Your MPIN Does Not Match From Inserted Database");
            } else {
                if (IS_PASSWORD_CHECK && Update_Visit_Date != null && Update_Visit_Date.equals("1")) {
                    if (CommonFunctions.checkNetIsAvailable(context)) {
                        AttempLogin();
                    } else {
                        AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE);
                    }
                } else if (IS_PASSWORD_CHECK && Update_Visit_Date == null) {
                    editor.putString(CommonString.KEY_USERNAME, user_id.toLowerCase());
                    if (!allLoginData.isEmpty() && allLoginData.get(0).getUserType() != null) {
                        editor.putString(CommonString.KEY_USER_TYPE, allLoginData.get(0).getUserType());
                    }
                    editor.commit();
                    if (!allLoginData.isEmpty() && !allLoginData.get(0).getImg().isEmpty()) {
                        if (db.isCheck_Old_Product(visit_date)) {
                            Intent in = new Intent(context, TimerActivity.class);
                            startActivity(in);
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            finish();
                        } else {
                            Intent in = new Intent(context, DealarBoardActivity.class);
                            startActivity(in);
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            finish();
                        }
                    } else {
                        Intent in = new Intent(context, StoreImageActivity.class);
                        startActivity(in);
                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                        finish();
                    }
                } else {
                    editor.putString(user_id, pinview_confirm.getValue());
                    if (!allLoginData.isEmpty() && allLoginData.get(0).getUserType() != null) {
                        editor.putString(CommonString.KEY_USER_TYPE, allLoginData.get(0).getUserType());
                    }
                    editor.putString(CommonString.KEY_USERNAME, user_id.toLowerCase());
                    editor.commit();
                    db.open();
                    db.updateLoginMpnData(user_id, pinview_confirm.getValue());
                    if (!allLoginData.isEmpty() && !allLoginData.get(0).getImg().isEmpty()) {
                        if (db.isCheck_Old_Product(visit_date)) {
                            Intent in = new Intent(context, TimerActivity.class);
                            startActivity(in);
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            finish();
                        } else {
                            Intent in = new Intent(context, DealarBoardActivity.class);
                            startActivity(in);
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            finish();
                        }
                    } else {
                        Intent in = new Intent(context, StoreImageActivity.class);
                        startActivity(in);
                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                        finish();
                    }
                }
            }

        } else if (v.getId() == R.id.btn_clear) {
            hideKeyboard(this);
            if (!pinview_start.getValue().isEmpty() && !pinview_confirm.getValue().isEmpty()) {
                pinview_start.clearValue();
                pinview_confirm.clearValue();
            } else if (!pinview_start.getValue().isEmpty() && pinview_confirm.getValue().isEmpty()) {
                pinview_start.clearValue();
            } else if (pinview_start.getValue().isEmpty() && !pinview_confirm.getValue().isEmpty()) {
                pinview_confirm.clearValue();
            }

            if (!IS_PASSWORD_CHECK) {
                pinview_start.requestFocus();
            } else {
                pinview_confirm.requestFocus();
            }

        } else if (v.getId() == R.id.btn_forgot_pin) {
            ((PinViewActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage("Forgot MPIN ?")
                    .setPositiveButton(android.R.string.yes, (dialogInterface, i) -> {
                        editor.putString(user_id, null);
                        editor.commit();
                        db.open();
                        db.updateLoginMpnData(user_id, null);
                        Intent in = new Intent(context, UserLoginActivity.class);
                        startActivity(in);
                        dialogInterface.cancel();
                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                        PinViewActivity.this.finish();
                    }).setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.dismiss());
            builder.show();
        }
    }


    private void AttempLogin() {
        try {

            loading = ProgressDialog.show(context, "Processing", "Please wait...", false, false);
            versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("UserName", user_id);
            jsonObject.put("Password", allLoginData.get(0).getPassword());
            jsonObject.put("CounterId", counterId);
            jsonObject.put("Latitude", lat);
            jsonObject.put("Longitude", lon);
            jsonObject.put("Appversion", app_ver);
            jsonObject.put("Attmode", "0");
            jsonObject.put("Networkstatus", "0");
            jsonObject.put("ModelNumber", model);
            jsonObject.put("Manufacturer", manufacturer);
            jsonObject.put("OSVersion", os_version);
            jsonObject.put("AppId", BuildConfig.APPLICATION_ID);

            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
                @SuppressLint("HardwareIds") String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
                jsonObject.put("IMEINumber1", android_id);
                jsonObject.put("IMEINumber2", android_id);
            } else {
                if (imeiNumbers != null && imeiNumbers.length > 0) {
                    jsonObject.put("IMEINumber1", imeiNumbers[0]);
                    if (imeiNumbers != null && imeiNumbers.length > 1) {
                        jsonObject.put("IMEINumber2", imeiNumbers[1]);
                    } else {
                        jsonObject.put("IMEINumber2", "0");
                    }
                } else {
                    jsonObject.put("IMEINumber1", "0");
                    jsonObject.put("IMEINumber2", "0");
                }
            }

            String jsonString = jsonObject.toString();
            try {
                final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).
                        writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
                RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString);
                Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
                PostApi api = adapter.create(PostApi.class);
                Call<ResponseBody> call = api.getLoginUserdetail(jsonData);

                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                        ResponseBody responseBody = response.body();
                        String data_Login = null;
                        if (responseBody != null && response.isSuccessful()) {
                            try {
                                assert response.body() != null;
                                data_Login = response.body().string();
                                data_Login = data_Login.substring(1, data_Login.length() - 1).replace("\\", "");
                                if (data_Login.contains("Changed")) {
                                    loading.dismiss();
                                    AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_CHANGED);
                                } else if (data_Login.contains("No data")) {
                                    loading.dismiss();
                                    AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_LOGIN_NO_DATA);
                                } else if (data_Login.equalsIgnoreCase(CommonString.KEY_FAILURE)) {
                                    AlertandMessages.showAlertlogin((Activity) context, CommonString.KEY_FAILURE + " Please try again");
                                    loading.dismiss();
                                } else {
                                    JSONObject obj = new JSONObject();
                                    obj.put("Downloadtype", "LoginTime");
                                    obj.put("Username", user_id);
                                    obj.put("Param1", counterId);
                                    obj.put("Param2", "");

                                    final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS)
                                            .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
                                    RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), obj.toString());
                                    Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
                                    PostApi api = adapter.create(PostApi.class);
                                    Call<String> call_login_tym = api.getDownloadAll(jsonData);
                                    final String finalData_Login = data_Login;
                                    call_login_tym.enqueue(new Callback<String>() {
                                        @Override
                                        public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                                            String responseBody = response.body();
                                            String data_login_time = null;
                                            if (responseBody != null && response.isSuccessful()) {
                                                try {
                                                    data_login_time = response.body();
                                                    assert data_login_time != null;
                                                    if (data_login_time.isEmpty()) {
                                                    } else {
                                                        BADeviceLoginGetterSetter data_login_Tym = null;
                                                        if (!data_login_time.contains("No Data")) {
                                                            data_login_Tym = new Gson().fromJson(data_login_time, BADeviceLoginGetterSetter.class);
                                                        }

                                                        loading.dismiss();
                                                        Gson gson = new Gson();
                                                        final BADeviceLoginGetterSetter userObject = gson.fromJson(finalData_Login, BADeviceLoginGetterSetter.class);
                                                        editor.putString(CommonString.KEY_USERNAME, user_id);
                                                        editor.putString(CommonString.KEY_PASSWORD, allLoginData.get(0).getPassword());
                                                        editor.putString(CommonString.KEY_DATE, userObject.getLOGIN().get(0).getVisitDate());
                                                        editor.putString(CommonString.KEY_PASSWORD_CHANGE, userObject.getLOGIN().get(0).getPasswordStatus());
                                                        editor.commit();
                                                        if (preferences.getString(CommonString.KEY_VERSION, "").equals(Integer.toString(versionCode))) {
                                                            loginGetterSetter = new LoginGetterSetter();
                                                            loginGetterSetter.setUserId(user_id);
                                                            loginGetterSetter.setPassword(allLoginData.get(0).getPassword());
                                                            loginGetterSetter.setVisitDate(visitdate);
                                                            loginGetterSetter.setUserType(userType);
                                                            if (data_login_Tym != null) {
                                                                loginGetterSetter.setUserLoginTym(data_login_Tym.getLoginTime().get(0).getLoginTime());
                                                            } else {
                                                                loginGetterSetter.setUserLoginTym("00:00");
                                                            }
                                                            db.open();
                                                            db.updateLoginTym(user_id, visit_date, loginGetterSetter.getUserLoginTym());
                                                            if (!userObject.getLOGIN().get(0).getPasswordStatus().isEmpty() && userObject.getLOGIN().get(0).
                                                                    getPasswordStatus().equalsIgnoreCase("Change")) {
                                                                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).
                                                                        setMessage("Your password has been reset. Please change your password").
                                                                        setCancelable(false).setPositiveButton(android.R.string.yes, (dialogInterface, i) -> {
                                                                            startActivity(new Intent(context, ChangePasswordActivity.class).putExtra(CommonString.KEY_PASSWORD_CHANGE,
                                                                                    userObject.getLOGIN().get(0).getPasswordStatus()).putExtra(CommonString.KEY_ACTIVITY, "PinView"));
                                                                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                                                            dialogInterface.dismiss();
                                                                            finish();
                                                                        });
                                                                builder.show();
                                                            } else {
                                                                loading.dismiss();
                                                                if (!allLoginData.isEmpty()) {
                                                                    if (allLoginData.get(0).getImg().isEmpty()) {
                                                                        startActivity(new Intent(context, StoreImageActivity.class));
                                                                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                                                        finish();
                                                                    } else {
                                                                        if (db.isCheck_Old_Product(visit_date)) {
                                                                            Intent in = new Intent(context, TimerActivity.class);
                                                                            startActivity(in);
                                                                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                                                            finish();
                                                                        } else {
                                                                            Intent in = new Intent(context, DealarBoardActivity.class);
                                                                            startActivity(in);
                                                                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                                                            finish();
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        } else {
                                                            Intent intent = new Intent(context, AutoUpdateActivity.class);
                                                            intent.putExtra(CommonString.KEY_PATH, preferences.getString(CommonString.KEY_PATH, ""));
                                                            startActivity(intent);
                                                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                                            finish();
                                                            loading.dismiss();
                                                        }
                                                    }
                                                } catch (Exception e) {
                                                    e.fillInStackTrace();
                                                    AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION);
                                                    loading.dismiss();
                                                }
                                            }
                                        }

                                        @Override
                                        public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                                            loading.dismiss();
                                            AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION);
                                        }
                                    });
                                }
                            } catch (Exception e) {
                                loading.dismiss();
                                e.fillInStackTrace();
                                AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")");

                            }
                        } else {
                            loading.dismiss();
                            AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_NO_RESPONSE_SERVER);
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                        loading.dismiss();
                        AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION);
                    }
                });

            } catch (Exception e) {
                loading.dismiss();
                e.fillInStackTrace();
                AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")");
            }

        } catch (PackageManager.NameNotFoundException | JSONException e) {
            loading.dismiss();
            AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")");

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkgpsEnableDevice();
        imeiNumbers = imei.getDeviceImei();
        createLocationRequest();
    }

    @SuppressLint("VisibleForTests")
    protected void createLocationRequest() {
        LocationRequest mLocationRequest = new LocationRequest();
        // Location updates intervals in sec
        // 5 sec
        int UPDATE_INTERVAL = 5000;
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        // 1 sec
        int FATEST_INTERVAL = 1000;
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // 10 meters
        int DISPLACEMENT = 5;
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    private void checkgpsEnableDevice() {
        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)) {
            enableLocationSettings();
        } else {
            if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                hasGPSDevice(context);
            }
        }
    }

    private void enableLocationSettings() {
        @SuppressLint("VisibleForTests") LocationRequest locationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) // new Priority constant
                .setInterval(30 * 1000)
                .setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest)
                .setAlwaysShow(true); // show dialog if GPS is off

        SettingsClient settingsClient = LocationServices.getSettingsClient(this);

        settingsClient.checkLocationSettings(builder.build())
                .addOnSuccessListener(locationSettingsResponse -> {
                    // All location settings are satisfied. You can request location updates here.
                }).addOnFailureListener(e -> {
                    if (e instanceof ResolvableApiException) {
                        try {
                            ResolvableApiException resolvable = (ResolvableApiException) e;
                            resolvable.startResolutionForResult((Activity) context, REQUEST_LOCATION);
                        } catch (IntentSender.SendIntentException sendEx) {
                            // Ignore the error.
                            sendEx.fillInStackTrace();
                        }
                    }
                });
    }

    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 check_keyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isAcceptingText()) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loading != null && loading.isShowing()) {
            loading.dismiss();
        }
    }
}
