package com.cpm.lorealbaMabeline.dailyactivity;

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.PackageInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.InputFilter;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.cpm.lorealbaMabeline.constant.CommonFunctions;
import com.cpm.lorealbaMabeline.gsonGetterSetter.JourneyPlan;
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.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.google.gson.Gson;
import com.cpm.lorealbaMabeline.AutoUpdateActivity;
import com.cpm.lorealbaMabeline.BuildConfig;
import com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.Get_IMEI_number.ImeiNumberClass;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.constant.AlertandMessages;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;
import com.cpm.lorealbaMabeline.forgotpassword.ForgotpasswordActity;
import com.cpm.lorealbaMabeline.gettersetter.LoginGetterSetter;
import com.cpm.lorealbaMabeline.gsonGetterSetter.BADeviceLoginGetterSetter;
import com.cpm.lorealbaMabeline.gsonGetterSetter.BaListGetterSetter;
import com.cpm.lorealbaMabeline.password.ChangePasswordActivity;
import com.cpm.lorealbaMabeline.pinviewactivity.PinViewActivity;
import com.cpm.lorealbaMabeline.retrofit.PostApi;

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 TabLoginActivity extends AppCompatActivity implements View.OnClickListener {
    private String counterId = "", str_updated_date = "0", visitdate = "", tag_from = "", userId, passwordData, app_ver, manufacturer, model, os_version;
    private Spinner sp_sppiner;
    private EditText password;
    private Button btncontinue;
    private Context context;
    private SharedPreferences preferences;
    private Lorealba_Database db;
    ArrayList<BaListGetterSetter> bsListData = new ArrayList<>();
    LoginGetterSetter loginGetterSetter;
    private int versionCode;
    ProgressDialog loading;
    private String[] imeiNumbers;
    private SharedPreferences.Editor editor = null;
    private double lat = 0.0, lon = 0.0;
    private static final int REQUEST_LOCATION = 1;
    private ImeiNumberClass imei;
    ArrayList<LoginGetterSetter> allLoginListData = new ArrayList<>();
    TextView forgot_password, versioncode_txt;
    private FirebaseAnalytics mFirebaseAnalytics;
    private FusedLocationProviderClient fusedLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_tab_login);
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(true);
        getViewId();
        setSppinerData();
        checkAndRequestPermissions();
        getLastLocation();

        /* To restrict Space Bar in Keyboard */
        InputFilter filter = (source, start, end, dest, dstart, dend) -> {
            for (int i = start; i < end; i++) {
                if (Character.isWhitespace(source.charAt(i))) {
                    return "";
                }
            }

            return null;
        };
        password.setFilters(new InputFilter[]{filter});
        showAlertForLogoutUser(false);
    }

    private void showAlertForLogoutUser(boolean clicked) {
        if (userId != null && !userId.isEmpty()) {
            JourneyPlan jcp = db.getBIDfromJCP(userId, counterId);
            if ((jcp != null && jcp.getCheckout() != null && jcp.getCheckout().equals("Y")) || preferences.getBoolean(CommonString.KEY_IS_CHECKOUT_DONE + userId + visitdate, false)) {
                new MaterialAlertDialogBuilder(this, R.style.MyMaterialAlertDialog)
                        .setTitle("Alert")
                        .setMessage("You have already checked-out in Store/Counter.You can't login again for today.").setCancelable(false)
                        .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                            dialog.dismiss();
                            finishAffinity();
                        }).show();
            } else if (clicked) {
                attemptLogin();
            }
        }
    }

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

    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(3 * 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();
        return providers.contains(LocationManager.GPS_PROVIDER);
    }

    @SuppressLint("SetTextI18n")
    void getViewId() {
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        preferences = PrefHelper.getPrefs(this);
        editor = preferences.edit();
        sp_sppiner = (Spinner) findViewById(R.id.sp_sppiner);
        password = (EditText) findViewById(R.id.password);
        btncontinue = (Button) findViewById(R.id.btncontinue);
        TextView user_type_login = (TextView) findViewById(R.id.user_type_login);
        TextView counter_name = (TextView) findViewById(R.id.counter_name);
        forgot_password = (TextView) findViewById(R.id.forgot_password);
        versioncode_txt = (TextView) findViewById(R.id.versioncode_txt);
        String tag_mode = "";
        if (getIntent().getSerializableExtra(CommonString.TAG_FROM) != null && getIntent().getSerializableExtra(CommonString.TAG_MODE) != null) {
            tag_from = getIntent().getStringExtra(CommonString.TAG_FROM);
            tag_mode = getIntent().getStringExtra(CommonString.TAG_MODE);
        } else {
            tag_from = preferences.getString(CommonString.TAG_FROM, "");
            tag_mode = preferences.getString(CommonString.TAG_MODE, "");
        }

        imei = new ImeiNumberClass(context);
        if (checkAndRequestPermissions()) {
            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();
        }
        user_type_login.setText(tag_mode);
        counterId = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        String counterCode = preferences.getString(CommonString.KEY_COUNTER_CODE, "");
        String counterName = preferences.getString(CommonString.KEY_COUNTER_NAME, "");
        visitdate = preferences.getString(CommonString.KEY_DATE, "");
        counter_name.setText("Counter Name : " + counterName + "\n" + "Counter Code : " + counterCode);
        db.open();
        bsListData = db.getBAListData(tag_from, counterId);
        btncontinue.setOnClickListener(v -> {
            if (CommonFunctions.checkNetIsAvailable(context)) {
                if (validation()) {
                    showAlertForLogoutUser(true);
                }
            } else {
                AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE, false);
            }
        });

        forgot_password.setOnClickListener(this);
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0);
            String version = pInfo.versionName;
            versioncode_txt.setText("Version : " + version +"-T");
        } catch (PackageManager.NameNotFoundException e) {
            e.fillInStackTrace();
            versioncode_txt.setText("Version : 0.0");
        }
    }

    private void setSppinerData() {
        ArrayAdapter<CharSequence> store_visited_adapter = new ArrayAdapter<CharSequence>(context, R.layout.spinner_custom_item);
        store_visited_adapter.add("- Select User -");
        for (int i = 0; i < bsListData.size(); i++) {
            store_visited_adapter.add(bsListData.get(i).getUserName());
        }
        store_visited_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
        sp_sppiner.setAdapter(store_visited_adapter);
        sp_sppiner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    userId = bsListData.get(position - 1).getUserName().toLowerCase();
                    db.open();
                    ArrayList<LoginGetterSetter> allLoginList = db.getlistAllUserIdData(visitdate, userId, true);
                    db.open();
                    if (!allLoginList.isEmpty()) {
                        db.open();
                        db.updateVisitDateLoginData(userId, visitdate);
                        str_updated_date = "1";
                    }
                    db.open();
                    allLoginListData = db.getlistAllUserIdData(visitdate, userId, false);
                    if (!allLoginListData.isEmpty()) {
                        LoginGetterSetter obj = allLoginListData.get(0);
                        if (obj != null && obj.getUserId() != null) {
                            String mpin = preferences.getString(userId, null);
                            Intent in;
                            if (mpin != null) {
                                in = new Intent(context, PinViewActivity.class).putExtra(CommonString.IS_PASSWORD_CHECK, true).putExtra(CommonString.KEY_USERNAME, userId).putExtra(CommonString.KEY_Update_Visit_Date, str_updated_date);
                                startActivity(in);
                                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                finish();
                            }
                        }
                    }
                } else {
                    userId = "";
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    private void attemptLogin() {
        passwordData = password.getText().toString().trim();
        AttempLogin();
    }


    private void AttempLogin() {
        try {
            loading = ProgressDialog.show(TabLoginActivity.this, "Processing", "Please wait...", false, false);
            versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("UserName", userId);
            jsonObject.put("Password", passwordData);
            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 {
                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 = null;
                        if (responseBody != null && response.isSuccessful()) {
                            try {
                                assert response.body() != null;
                                data = response.body().string();
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data != null && data.equalsIgnoreCase(CommonString.KEY_FAILURE)) {
                                    AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.KEY_FAILURE + " Please try again");
                                    loading.dismiss();
                                }
                                else if (data != null && data.contains("Changed")) {
                                    loading.dismiss();
                                    AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_CHANGED);
                                }
                                else if (data != null && data.contains("Lockout")) {
                                    loading.dismiss();
                                    editor.putBoolean(CommonString.KEY_LOCKOUT + userId + visitdate, true);
                                    editor.commit();
                                    AlertandMessages.closeApp((Activity) context, CommonString.MESSAGE_LOCKED);
                                }
                                else if (data != null && data.contains("No data")) {
                                    loading.dismiss();
                                    AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_LOGIN_NO_DATA);
                                } else {
                                    JSONObject obj = new JSONObject();
                                    obj.put("Downloadtype", "LoginTime");
                                    obj.put("Username", userId);
                                    obj.put("Param1", counterId);
                                    obj.put("Param2", "");

                                    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 = data;
                                    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()) {
                                                        BADeviceLoginGetterSetter data_login_Tym = null;
                                                        if (!data_login_time.contains("No Data")) {
                                                            data_login_Tym = new Gson().fromJson(data_login_time, BADeviceLoginGetterSetter.class);
                                                        }
                                                        Gson gson = new Gson();
                                                        final BADeviceLoginGetterSetter userObject = gson.fromJson(finalData, BADeviceLoginGetterSetter.class);
                                                        editor.putString(CommonString.KEY_USERNAME, userId.toLowerCase());
                                                        editor.putString(CommonString.KEY_PASSWORD, passwordData);
                                                        editor.putString(CommonString.KEY_DATE, userObject.getLOGIN().get(0).getVisitDate());
                                                        editor.putString(CommonString.KEY_PASSWORD_CHANGE, userObject.getLOGIN().get(0).getPasswordStatus());
                                                        editor.commit();

                                                        Bundle bundle = new Bundle();
                                                        bundle.putString(FirebaseAnalytics.Param.ITEM_ID, userId.toLowerCase());
                                                        bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, CommonString.KEY_LOGIN_DATA);
                                                        bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "Data");
                                                        mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
                                                        FirebaseCrashlytics.getInstance().setUserId(userId.toLowerCase());

                                                        if (preferences.getString(CommonString.KEY_VERSION, "").equals(Integer.toString(versionCode))) {
                                                            loginGetterSetter = new LoginGetterSetter();
                                                            loginGetterSetter.setUserId(userId.toLowerCase());
                                                            loginGetterSetter.setPassword(passwordData);
                                                            loginGetterSetter.setVisitDate(visitdate);
                                                            loginGetterSetter.setUserType(tag_from);
                                                            loginGetterSetter.setUser_checkout("0");
                                                            if (data_login_Tym != null) {
                                                                loginGetterSetter.setUserLoginTym(data_login_Tym.getLoginTime().get(0).getLoginTime());
                                                            } else {
                                                                loginGetterSetter.setUserLoginTym("00:00");
                                                            }

                                                            db.open();
                                                            if (!db.ischeck_login_data(userId.toLowerCase())) {
                                                                db.open();
                                                                db.insertLoginData(loginGetterSetter);
                                                            }
                                                            loading.dismiss();
                                                            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, "Start"));
                                                                                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                                                                    dialogInterface.dismiss();
                                                                                    finish();
                                                                                });

                                                                builder.show();
                                                            } else {
                                                                Intent in = new Intent(getApplicationContext(), PinViewActivity.class);
                                                                in.putExtra(CommonString.IS_PASSWORD_CHECK, false);
                                                                in.putExtra(CommonString.KEY_USERNAME, userId.toLowerCase());
                                                                startActivity(in);
                                                                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                                                finish();
                                                                loading.dismiss();
                                                            }
                                                        } 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();
                                                    loading.dismiss();
                                                    AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + " - " + e.toString());
                                                }
                                            } else {
                                                loading.dismiss();
                                                AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_NO_RESPONSE_SERVER);
                                            }
                                        }

                                        @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(TabLoginActivity.this, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e.toString() + ")");

                            }
                        } else {
                            loading.dismiss();
                            AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_NO_RESPONSE_SERVER);
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                        loading.dismiss();
                        if (t instanceof Exception) {
                            AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + "(" + t.getMessage() + ")");
                        } else {
                            AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_SOCKETEXCEPTION);
                        }
                    }
                });

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

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

        }
    }


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

    public boolean validation() {
        boolean value = true;
        if (sp_sppiner.getSelectedItemPosition() == 0) {
            value = false;
            showMessage("Please Select User");
        } else if (password.getText().toString().isEmpty()) {
            value = false;
            showMessage("Please fill Password");
        }
        return value;
    }

    public void showMessage(String message) {
        Snackbar.make(btncontinue, message, Snackbar.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.forgot_password) {
            startActivity(new Intent(context, ForgotpasswordActity.class).putExtra(CommonString.TAG_OBJECT, bsListData));
        }
    }

    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()]), CommonString.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 == CommonString.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");
                    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
                    getLastLocation();
                    getDeviceName();
                    imeiNumbers = imei.getDeviceImei();
                } else {
                    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,Call and Camera Services Permission required for this app",
                                (dialog, which) -> {
                                    switch (which) {
                                        case DialogInterface.BUTTON_POSITIVE:
                                            checkAndRequestPermissions();
                                            break;
                                        case 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);
                                            break;
                                    }
                                });
                    } else {
                        Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    }

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

    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();
                        }
                    });
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }
}



