package com.cpm.lorealbaautomation;

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

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.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
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.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.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.firebase.crashlytics.FirebaseCrashlytics;
import com.google.gson.Gson;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.Get_IMEI_number.ImeiNumberClass;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.dailyactivity.NotificationDetailActivity;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.CounterDeviceLoginGetterSetter;
import com.cpm.lorealbaautomation.retrofit.PostApi;
import com.cpm.lorealbaautomation.upload.ManualUploadActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
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 IMEILoginActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private String[] imeiNumbers;
    private String app_ver;
    private Context context;
    private static final int LOGIN_AFTER_NOTIFICATION = 2;
    ProgressDialog loading = null;
    private Retrofit adapter;
    private SharedPreferences preferences = null;
    private SharedPreferences.Editor editor = null;
    private double lat = 0.0;
    private double lon = 0.0;
    private int versionCode;
    private String manufacturer;
    private String model;
    private String os_version;
    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 static final int PERMISSION_ALL = 99;
    private ImeiNumberClass imei;
    Lorealba_Database db;
    String title = "", body = "", path = "", counter_id, type, visit_date;
    TextView versioncode_txt;
    LinearLayout rl_counterlogin;
    CounterDeviceLoginGetterSetter userapp_databaseObject = null;

    @SuppressLint("SetTextI18n")
    @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_counter_login);
        FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(true);
        if (getIntent().getExtras() != null) {
            long value = 0;
            for (String key : getIntent().getExtras().keySet()) {
                if (key.equalsIgnoreCase("title")) {
                    title = getIntent().getExtras().getString(key);
                } else if (key.equalsIgnoreCase("body")) {
                    body = getIntent().getExtras().getString(key);
                } else if (key.equalsIgnoreCase("path")) {
                    path = getIntent().getExtras().getString(key);
                } else if (key.equalsIgnoreCase("Mediatype")) {
                    type = getIntent().getExtras().getString(key);
                }
            }
            assert title != null;
            if (!title.isEmpty() && !Objects.requireNonNull(body).isEmpty()) {
                context = this;
                db = new Lorealba_Database(context);
                db.open();
                value = db.insertNotificationData(title, body, path, visit_date, type, counter_id);
                if (value > 0) {
                    Toast.makeText(context, "Notification Inserted", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Notification Not Inserted", Toast.LENGTH_SHORT).show();
                }
            } else {
                getViewId();
            }

            if (!title.isEmpty()) {
                Intent in = new Intent(this, NotificationDetailActivity.class);
                in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                in.putExtra("Type", type);
                in.putExtra("Title", title);
                in.putExtra("Body", body);
                in.putExtra("Path", path);
                in.putExtra("KEY_ID", value + "");
                startActivityForResult(in, LOGIN_AFTER_NOTIFICATION);
            }
        } else {
            getViewId();
        }

        versioncode_txt = (TextView) findViewById(R.id.versioncode_txt);
        rl_counterlogin = (LinearLayout) findViewById(R.id.rl_counterlogin);
        rl_counterlogin.setVisibility(View.GONE);
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0);
            String version = pInfo.versionName;
            versioncode_txt.setText("Version : " + version);
        } catch (PackageManager.NameNotFoundException e) {
            e.fillInStackTrace();
            versioncode_txt.setText("Version : 0.0");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        context = this;
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }

        checkgpsEnableDevice();
        if (checkAndRequestPermissions()) {
            imeiNumbers = imei.getDeviceImei();
            getDeviceName();
        }
    }

    @SuppressLint("VisibleForTests")
    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        if (mLocationRequest != null)
            mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        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)) {
            enableLoc();
        } else if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(context)) {
        }
    }

    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);
    }

    @SuppressLint("VisibleForTests")
    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(result1 -> {
                final Status status = result1.getStatus();
                if (status.getStatusCode() == 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.
                    }
                }
            });
        }
    }


    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, (Activity) context, PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(context, 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();
        }
    }


    @SuppressLint("ObsoleteSdkInt")
    private void AttempLogin() {
        try {
            try {
                app_ver = String.valueOf(getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
            } catch (PackageManager.NameNotFoundException e) {
                // TODO Auto-generated catch block
                e.fillInStackTrace();
            }

            loading = ProgressDialog.show(IMEILoginActivity.this, "Processing", "Please wait...", false, false);
            versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
            JSONObject jsonObject = new JSONObject();

            jsonObject.put("OSVersion", os_version);
            jsonObject.put("Manufacturer", manufacturer);
            jsonObject.put("ModelNumber", model);
            jsonObject.put("Networkstatus", "0");
            jsonObject.put("Attmode", "0");
            jsonObject.put("Appversion", app_ver);
            jsonObject.put("Latitude", lat);
            jsonObject.put("Longitude", lon);
            jsonObject.put("CounterCode", "0");
            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);
            } else {
                if (imeiNumbers != null && imeiNumbers.length > 0) {
                    jsonObject.put("IMEINumber1", imeiNumbers[0]);
                } else {
                    jsonObject.put("IMEINumber1", "0");
                }
            }

            String jsonString = jsonObject.toString();
            Log.e("jsonlogindata", jsonString);
            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);
                adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
                PostApi api = adapter.create(PostApi.class);
                Call<ResponseBody> call = api.getLogindetail(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("\\", "");
                                Gson gson = new Gson();
                                final CounterDeviceLoginGetterSetter userObject = gson.fromJson(data, CounterDeviceLoginGetterSetter.class);
                                if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) {
                                    AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.KEY_FAILURE + " Please try again");
                                    loading.dismiss();

                                    if (loading != null && loading.isShowing()) {
                                        loading.dismiss();
                                    }
                                } else if (userObject != null) {
                                    JSONObject jsonObject1 = new JSONObject();
                                    jsonObject1.put("Downloadtype", "AppDatabaseName");
                                    jsonObject1.put("Username", "");
                                    jsonObject1.put("Param1", "");
                                    jsonObject1.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"), jsonObject1.toString());
                                    adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
                                    PostApi api = adapter.create(PostApi.class);
                                    Call<String> call_appdatabase = api.getDownloadAll(jsonData);
                                    call_appdatabase.enqueue(new Callback<String>() {
                                        @Override
                                        public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                                            String responseBody_dab = response.body();
                                            String data_datab = null;
                                            if (responseBody_dab != null && response.isSuccessful()) {
                                                data_datab = response.body();
                                                assert data_datab != null;
                                                if (!data_datab.isEmpty()) {
                                                    if (!data_datab.contains("No Data")) {
                                                        userapp_databaseObject = new Gson().fromJson(data_datab, CounterDeviceLoginGetterSetter.class);
                                                    }
                                                }
                                                if (userapp_databaseObject != null && !userapp_databaseObject.getAppDatabaseName().isEmpty()) {
                                                    int temp_db_versioncode = preferences.getInt(CommonString.KEY_TEMP_DB_VERSION, 0);
                                                    if (userapp_databaseObject.getAppDatabaseName().get(0).getAppVersion() != temp_db_versioncode) {
                                                        ////for Database delete
                                                        delete_local_database();
                                                    }
                                                    editor.putInt(CommonString.KEY_TEMP_DB_VERSION, userapp_databaseObject.getAppDatabaseName().get(0).getAppVersion());
                                                }
                                                editor.putString(CommonString.KEY_VERSION, userObject.getCounterDeviceLogin().get(0).getAppVersion().toString());
                                                editor.putString(CommonString.KEY_PATH, userObject.getCounterDeviceLogin().get(0).getAppPath());
                                                editor.putString(CommonString.KEY_DATE, userObject.getCounterDeviceLogin().get(0).getVisitDate());
                                                editor.putString(CommonString.KEY_COUNTER_ID, userObject.getCounterDeviceLogin().get(0).getCounterId().toString());
                                                editor.putString(CommonString.KEY_COUNTER_CODE, userObject.getCounterDeviceLogin().get(0).getCounterCode());
                                                editor.putString(CommonString.KEY_COUNTER_NAME, userObject.getCounterDeviceLogin().get(0).getCounterName());
                                                editor.apply();
                                                if (userObject.getCounterDeviceLogin().get(0).getAppVersion().equals(versionCode)) {
                                                    //-------upload previous day pending data---------------------
                                                    if (userObject.getCounterDeviceLogin().get(0).getCounterId().equals(0)) {
                                                        loading.dismiss();
                                                        if (loading != null && loading.isShowing()) {
                                                            loading.dismiss();
                                                        }
                                                        Intent intent = new Intent(getBaseContext(), CounterLoginActivity.class);
                                                        startActivity(intent);
                                                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                                        finish();
                                                    } else {
                                                        db.open();
                                                        String datee = userObject.getCounterDeviceLogin().get(0).getVisitDate();
                                                        if (!db.getmasterTransaction(datee, userObject.getCounterDeviceLogin().get(0).getCounterId().toString(), true).isEmpty()
                                                                || !checkincomplete_upload_data(datee,
                                                                userObject.getCounterDeviceLogin().get(0).getCounterId().toString(), db, true)) {
                                                            startActivity(new Intent(context, ManualUploadActivity.class).putExtra(CommonString.TAG_OBJECT,
                                                                    userObject.getCounterDeviceLogin().get(0).getCounterId()));
                                                        } else {
                                                            Intent intent = new Intent(getBaseContext(), UserLoginActivity.class);
                                                            startActivity(intent);
                                                        }
                                                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                                        IMEILoginActivity.this.finish();
                                                        if (loading != null && loading.isShowing()) {
                                                            loading.dismiss();
                                                        }
                                                    }
                                                } else {
                                                    loading.dismiss();
                                                    if (loading != null && loading.isShowing()) {
                                                        loading.dismiss();
                                                    }
                                                    Intent intent = new Intent(getBaseContext(), AutoUpdateActivity.class);
                                                    intent.putExtra(CommonString.KEY_PATH, preferences.getString(CommonString.KEY_PATH, ""));
                                                    startActivity(intent);
                                                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                                    IMEILoginActivity.this.finish();
                                                }
                                            } else {
                                                loading.dismiss();
                                                if (loading != null && loading.isShowing()) {
                                                    loading.dismiss();
                                                }
                                                AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_NO_RESPONSE_SERVER);
                                            }
                                        }

                                        @Override
                                        public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                                            loading.dismiss();
                                            if (loading != null && loading.isShowing()) {
                                                loading.dismiss();
                                            }
                                            AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION);

                                        }
                                    });

                                } else {
                                    loading.dismiss();
                                    if (loading != null && loading.isShowing()) {
                                        loading.dismiss();
                                    }

                                    AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_NO_RESPONSE_SERVER);
                                }

                            } catch (Exception e) {
                                loading.dismiss();
                                FirebaseCrashlytics.getInstance().recordException(e);
                                if (loading != null && loading.isShowing()) {
                                    loading.dismiss();
                                }

                                e.fillInStackTrace();
                                AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + " - " + e.toString());
                            }
                        } else {
                            loading.dismiss();
                            if (loading != null && loading.isShowing()) {
                                loading.dismiss();
                            }
                            AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_NO_RESPONSE_SERVER);
                        }
                    }

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

                    }
                });

            } catch (Exception e) {
                loading.dismiss();
                if (loading != null && loading.isShowing()) {
                    loading.dismiss();
                }
                e.fillInStackTrace();
                AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + " - " + e.toString());

            }

        } catch (PackageManager.NameNotFoundException e) {
            loading.dismiss();
            if (loading != null && loading.isShowing()) {
                loading.dismiss();
            }
            AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + " - " + e.toString());

        } catch (JSONException e) {
            loading.dismiss();
            if (loading != null && loading.isShowing()) {
                loading.dismiss();
            }
        }
    }

    public void getDeviceName() {
        try {
            manufacturer = Build.MANUFACTURER;
            model = Build.MODEL;
            os_version = Build.VERSION.RELEASE;
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    private void delete_local_database() {
        boolean deleted = true;
        try {
            File datadbfile = Environment.getDataDirectory();
            String currentDBPath = "//data//" + BuildConfig.APPLICATION_ID + "//databases//" + Lorealba_Database.DATABASE_NAME;
            File currentDB = new File(datadbfile, currentDBPath);
            deleted = SQLiteDatabase.deleteDatabase(currentDB);
            if (deleted) {
                AlertandMessages.showToastMsg(context, "Database Deleted Successfully");
            }
            new Lorealba_Database(context).open();
        } catch (Exception e) {
            e.fillInStackTrace();
        }

    }


    @Override
    public void onConnected(Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(context, 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();
            }

            startLocationUpdates();
        }
    }

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

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

    @Override
    public void onLocationChanged(Location location) {
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }

    }

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

    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);
            }
        }
    }

    void getViewId() {
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        preferences = PrefHelper.getPrefs(context);
        counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        editor = preferences.edit();
        imei = new ImeiNumberClass(context);
        if (checkAndRequestPermissions()) {
            imeiNumbers = imei.getDeviceImei();
            getDeviceName();
            AttempLogin();
        }

        try {
            app_ver = String.valueOf(getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.fillInStackTrace();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case (LOGIN_AFTER_NOTIFICATION): {
                if (resultCode == Activity.RESULT_OK) {
                    // TODO Extract the data returned from the child Activity.
                    getViewId();
                }
                break;
            }
        }
    }

    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(DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(this).setMessage("Location,File,Call and Camera Services Permission required for this app").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);
        Log.d("", "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){
                    getDeviceName();
                    imeiNumbers = imei.getDeviceImei();
                    AttempLogin();
                }

                Log.d("", "sms & location services permission granted");
            } else {
                Log.d("", "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(
                            (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();
                }
            }
        }
    }

    public class MultiPurposeDialog extends Dialog {
        public MultiPurposeDialog(Context context) {
            super(context);
            WindowManager.LayoutParams wmLayoutParams = Objects.requireNonNull(getWindow()).getAttributes();
            wmLayoutParams.gravity = Gravity.CENTER;
            getWindow().setAttributes(wmLayoutParams);
            setTitle(null);
            setCancelable(false);
            setOnCancelListener(null);
            LinearLayout layout = new LinearLayout(context);
            layout.setOrientation(LinearLayout.VERTICAL);
        }
    }

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