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.DatePickerDialog;
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.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.provider.Settings;

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.cpm.lorealbaautomation.delegates.PrefHelper;

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

import android.os.Bundle;
import android.text.InputFilter;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.Get_IMEI_number.ImeiNumberClass;
import com.cpm.lorealbaautomation.adapter.LeaveDetailAdapter;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.dailyactivity.NotificationDetailActivity;
import com.cpm.lorealbaautomation.databinding.DialogApplyLeaveBinding;
import com.cpm.lorealbaautomation.gsonGetterSetter.CounterDeviceLoginGetterSetter;
import com.cpm.lorealbaautomation.retrofit.PostApi;
import com.cpm.lorealbaautomation.tbaleavemodel.Common;
import com.cpm.lorealbaautomation.tbaleavemodel.TBAMESearch;
import com.cpm.lorealbaautomation.upload.ManualUploadActivity;
import com.cpm.lorealbaautomation.utils.DrawableClickListener;

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

import java.util.ArrayList;
import java.util.Calendar;
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 CounterLoginActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    String str_counter_id = "";
    EditText counter_id;
    Button btncontinue;
    private String[] imeiNumbers;
    private String app_ver;
    private Context context;
    ProgressDialog loading;
    private SharedPreferences.Editor editor = null;
    private double lat = 0.0;
    private double lon = 0.0;
    private String manufacturer;

    private String model;
    private String os_version;
    private static final int REQUEST_LOCATION = 1;
    private static final int PERMISSIONS_REQUEST_READ_PHONE_STATE = 999;
    private ImeiNumberClass imei;
    Lorealba_Database db;
    String title = "", body = "", path = "", visited_date = "", type;
    LinearLayout rlMarkLeave;
    TextView versioncode_txt;

    Spinner leaveSpin;
    int mYear, mMonth, mDay;
    DatePickerDialog dpd;
    Calendar c;
    private TBAMESearch tbameSearch = null;
    private CustomDialogLeaveApply customDialogLeave = null;
    String blockCharacterSet = "[';:-+{('}<!>@=#$%^&*?)\"]";
    InputFilter filter = (source, start, end, dest, dstart, dend) -> {
        if (source != null && blockCharacterSet.contains(("" + source))) {
            return "";
        }
        return null;
    };
    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_counter);
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        getViewId();
        callSpinAdapter();
        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 void callSpinAdapter() {
        ArrayAdapter<String> reason_adapter = new ArrayAdapter<String>(context, R.layout.spinner_leave);
        reason_adapter.add("Mark Leave(TBA/ME)");
        reason_adapter.add("Mark Leave");
        reason_adapter.add("Leave History");
        leaveSpin.setAdapter(reason_adapter);
        reason_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        leaveSpin.setOnItemSelectedListener(this);
    }

    @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]);
                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((Activity) context);
                    getLastLocation();
                    getDeviceName();
                    imeiNumbers = imei.getDeviceImei();
                }
                // Check for both permissions
                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) -> {
                            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;
                            }
                        });
                    }
                    //permission is denied (and never ask again is  checked)
                    //shouldShowRequestPermissionRationale will return false
                    else {
                        Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG).show();
                        //                           //proceed with logic by disabling the related features or quit the app.
                    }
                }
            }
        }
    }

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

    }
    @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(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 AttempLogin() {
        try {
            loading = ProgressDialog.show(CounterLoginActivity.this, "Processing", "Please wait...", false, false);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Latitude", lat);
            jsonObject.put("Longitude", lon);
            jsonObject.put("Appversion", app_ver);
            jsonObject.put("Attmode", "0");
            jsonObject.put("Networkstatus", "0");
            jsonObject.put("Manufacturer", manufacturer);
            jsonObject.put("ModelNumber", model);
            jsonObject.put("OSVersion", os_version);
            jsonObject.put("CounterCode", str_counter_id);
            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();
            //test("jsondata",jsonString);
            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.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();
                                CounterDeviceLoginGetterSetter userObject = gson.fromJson(data, CounterDeviceLoginGetterSetter.class);
                                if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) {
                                    AlertandMessages.showAlertCounterlogin(CounterLoginActivity.this, CommonString.KEY_FAILURE + " Please try again");
                                    loading.dismiss();
                                } else if (userObject != null && userObject.getCounterDeviceLogin().get(0).getCounterId().equals(0)) {
                                    loading.dismiss();
                                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                    builder.setTitle(R.string.parinaam);
                                    builder.setMessage("This counter code is already mapped to different device.please contact your supervisor.").setCancelable(false).setPositiveButton(android.R.string.ok, (dialog, id) -> dialog.dismiss());
                                    AlertDialog alert = builder.create();
                                    alert.show();
                                } else {
                                    assert userObject != null;
                                    if (userObject.getCounterDeviceLogin().get(0).getCounterId().equals(-1)) {
                                        loading.dismiss();
                                        AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam);
                                        builder.setMessage("This counter not exist").setCancelable(false).setPositiveButton(android.R.string.ok, (dialog, id) -> dialog.dismiss());
                                        AlertDialog alert = builder.create();
                                        alert.show();
                                    } else {
                                        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.commit();
                                        ////chjecking previus data is pending
                                        db.open();
                                        if (!db.getmasterTransaction(userObject.getCounterDeviceLogin().get(0).getVisitDate(),
                                                userObject.getCounterDeviceLogin().get(0).getCounterId().toString(), true).isEmpty()
                                                || !checkincomplete_upload_data(userObject.getCounterDeviceLogin().get(0).getVisitDate(),
                                                userObject.getCounterDeviceLogin().get(0).getCounterId().toString(), db, true)) {
                                            startActivity(new Intent(context, ManualUploadActivity.class).putExtra(CommonString.TAG_OBJECT,
                                                    userObject.getCounterDeviceLogin().get(0).getCounterId()));
                                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                            finish();
                                        } else {
                                            Intent intent = new Intent(getBaseContext(), UserLoginActivity.class);
                                            startActivity(intent);
                                            finish();
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                loading.dismiss();
                                e.fillInStackTrace();
                                AlertandMessages.showAlertlogin(CounterLoginActivity.this, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e.toString() + ")");
                            }
                        } else {
                            loading.dismiss();
                            AlertandMessages.showAlertlogin(CounterLoginActivity.this, CommonString.MESSAGE_NO_RESPONSE_SERVER);
                        }
                    }

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

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

        }
    }

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

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

    @SuppressLint("SetTextI18n")
    void getViewId() {
        context = this;
        SharedPreferences preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        counter_id = (EditText) findViewById(R.id.counter_id);
        db = new Lorealba_Database(this);
        db.open();
        leaveSpin = (com.cpm.lorealbaautomation.utils.Spinner) findViewById(R.id.leaveSpin);
        versioncode_txt = (TextView) findViewById(R.id.versioncode_txt);
        rlMarkLeave = (LinearLayout) findViewById(R.id.rlMarkLeave);
        btncontinue = (Button) findViewById(R.id.btncontinue);
        rlMarkLeave.setVisibility(View.VISIBLE);
        btncontinue.setOnClickListener(this);
        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();
        }

        if (getIntent().getExtras() != null) {
            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("Currentdate")) {
                    visited_date = getIntent().getExtras().getString(key);
                } else if (key.equalsIgnoreCase("type")) {
                    type = getIntent().getExtras().getString(key);
                }
            }

            assert title != null;
            assert body != null;
            if (!title.equalsIgnoreCase("") && !body.equalsIgnoreCase("")) {
                db.open();
                long value = db.insertNotificationData(title, body, path, visited_date, type, str_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();
                }
            }

            if (!title.isEmpty()) {
                Intent in = new Intent(this, NotificationDetailActivity.class);
                in.putExtra("Type", type);
                in.putExtra("Title", title);
                in.putExtra("Body", body);
                in.putExtra("Path", path);
                startActivity(in);
            }
        }


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

    }

    public boolean CheckNetAvailability() {
        boolean connected = false;
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Objects.requireNonNull(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)).getState() == NetworkInfo.State.CONNECTED || Objects.requireNonNull(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)).getState() == NetworkInfo.State.CONNECTED) {
            connected = true;
        }
        return connected;
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btncontinue) {
            str_counter_id = counter_id.getText().toString().trim().replaceAll("[&^<>{}'$]", "");
            if (str_counter_id.isEmpty()) {
                Toast.makeText(this, "Please enter Counter Code", Toast.LENGTH_SHORT).show();
            } else if (CheckNetAvailability()) {
                AttempLogin();
            } else {
                Toast.makeText(this, "No internet connection! try again later", Toast.LENGTH_LONG).show();
            }
        }

    }

    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 onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (position != 0) {
            customDialogLeave = new CustomDialogLeaveApply((AppCompatActivity) context);
            customDialogLeave.show();
        }
    }

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

    }

    public class CustomDialogLeaveApply extends Dialog {
        private CustomDialogLeaveApply oneButtonDialog;
        private DialogApplyLeaveBinding binding = null;

        public CustomDialogLeaveApply(AppCompatActivity activity) {
            super(activity);
        }

        public CustomDialogLeaveApply getInstance(AppCompatActivity activity) {
            return oneButtonDialog = (oneButtonDialog == null) ? new CustomDialogLeaveApply(activity) : oneButtonDialog;
        }

        @SuppressLint("SetTextI18n")
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            binding = DialogApplyLeaveBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());
            if (leaveSpin.getSelectedItem().toString().equals("Leave History")) {
                Objects.requireNonNull(getWindow()).setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
            }
            Objects.requireNonNull(getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            binding.edtapplyForleaveReason.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(550)});
            binding.imgClose.setOnClickListener(v -> {
                leaveSpin.setSelection(0);
                dismiss();
            });

            binding.etEmployeeCode.setOnEditorActionListener((v, actionId, event) -> {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    // Your action on done
                    if (Objects.requireNonNull(binding.etEmployeeCode.getText()).toString().isEmpty()) {
                        AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code");
                    } else {
                        CommonFunctions.dismissKeyboard(binding.getRoot());
                        getEmployeeDetails(binding.etEmployeeCode.getText().toString(), binding.tvEmpName, binding.tvEmpCode,
                                binding.tvEmpDesignation);
                    }
                    return true;
                }
                return false;
            });

            binding.etEmployeeCode.setDrawableClickListener(target -> {
                if (Objects.requireNonNull(target) == DrawableClickListener.DrawablePosition.RIGHT) {
                    if (Objects.requireNonNull(binding.etEmployeeCode.getText()).toString().isEmpty()) {
                        AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code");
                    } else {
                        CommonFunctions.dismissKeyboard(binding.getRoot());
                        getEmployeeDetails(binding.etEmployeeCode.getText().toString(), binding.tvEmpName, binding.tvEmpCode, binding.tvEmpDesignation);
                    }
                }
            });

            binding.etEmployeeCodeforHistory.setOnEditorActionListener((v, actionId, event) -> {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    // Your action on done
                    if (Objects.requireNonNull(binding.etEmployeeCodeforHistory.getText()).toString().isEmpty()) {
                        AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code");
                    } else {
                        ///API call
                        getLeaveHistory(binding);
                        CommonFunctions.dismissKeyboard(binding.getRoot());
                    }
                    return true;
                }
                return false;
            });

            binding.etEmployeeCodeforHistory.setDrawableClickListener(target -> {
                if (Objects.requireNonNull(target) == DrawableClickListener.DrawablePosition.RIGHT) {
                    if (Objects.requireNonNull(binding.etEmployeeCodeforHistory.getText()).toString().isEmpty()) {
                        AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code");
                    } else {
                        ///API call
                        getLeaveHistory(binding);
                        CommonFunctions.dismissKeyboard(binding.getRoot());
                    }
                }
            });

            binding.rlFromDateInfo.setOnClickListener(v -> {
                if (binding.radioBFullday.isChecked() || binding.radioHalfDay.isChecked()) {
                    c = Calendar.getInstance();
                    mYear = c.get(Calendar.YEAR);
                    mMonth = c.get(Calendar.MONTH);
                    mDay = c.get(Calendar.DAY_OF_MONTH);
                    // Launch Date Picker Dialog
                    dpd = new DatePickerDialog(context, (view, year, monthOfYear, dayOfMonth) -> {
                        String month_of_year = "", start_day_Of_Month = "";
                        if ((monthOfYear + 1) < 10) {
                            month_of_year = "0" + (monthOfYear + 1);
                        } else {
                            month_of_year = String.valueOf(monthOfYear + 1);
                        }
                        if ((dayOfMonth) < 10) {
                            start_day_Of_Month = "0" + dayOfMonth;
                        } else {
                            start_day_Of_Month = String.valueOf(dayOfMonth);
                        }
                        String cmp_date = month_of_year + "/" + start_day_Of_Month + "/" + year;
                        binding.tvFromDate.setText(cmp_date);
                        binding.tvToDate.setText("");
                        if (binding.radioHalfDay.isChecked()) {
                            binding.tvToDate.setText(cmp_date);
                        }
                    }, mYear, mMonth, mDay);
                    Calendar calendar = Calendar.getInstance();
                    dpd.getDatePicker().setMinDate(calendar.getTimeInMillis() - 1000);
                    calendar = Calendar.getInstance();
                    calendar.add(Calendar.MONTH, 2);
                    dpd.getDatePicker().setMaxDate(calendar.getTimeInMillis());
                    dpd.show();
                }
            });

            binding.rlToDateInfo.setOnClickListener(v -> {
                if (binding.radioBFullday.isChecked() && !binding.tvFromDate.getText().toString().isEmpty()) {
                    c = Calendar.getInstance();
                    mYear = c.get(Calendar.YEAR);
                    mMonth = c.get(Calendar.MONTH);
                    mDay = c.get(Calendar.DAY_OF_MONTH);
                    dpd = new DatePickerDialog(context, (view, year, monthOfYear, dayOfMonth) -> {
                        try {
                            String month_of_year = "", day_Of_Month = "";
                            if ((monthOfYear + 1) < 10) {
                                month_of_year = "0" + (monthOfYear + 1);
                            } else {
                                month_of_year = String.valueOf(monthOfYear + 1);
                            }
                            if ((dayOfMonth) < 10) {
                                day_Of_Month = "0" + dayOfMonth;
                            } else {
                                day_Of_Month = String.valueOf(dayOfMonth);
                            }

                            binding.tvToDate.setText(month_of_year + "/" + day_Of_Month + "/" + year);

                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    }, mYear, mMonth, mDay);
                    String[] fromDate = binding.tvFromDate.getText().toString().split("/");
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Integer.parseInt(fromDate[2]), Integer.parseInt(fromDate[0]) - 1, Integer.parseInt(fromDate[1]));
                    dpd.getDatePicker().setMinDate(calendar.getTimeInMillis());
                    calendar = Calendar.getInstance();
                    calendar.set(Integer.parseInt(fromDate[2]), Integer.parseInt(fromDate[0]) + 1, Integer.parseInt(fromDate[1]));
                    dpd.getDatePicker().setMaxDate(calendar.getTimeInMillis());
                    dpd.show();
                }
            });
        }

        @SuppressLint("SetTextI18n")
        @Override
        protected void onStart() {
            super.onStart();
            setCancelable(false);
            if (leaveSpin.getSelectedItem().equals("Mark Leave")) {
                binding.tvDialogTitle.setText("Apply For Leave");
                binding.btnSubmit.setVisibility(View.VISIBLE);
                binding.rlApplyLeaveDetail.setVisibility(View.VISIBLE);
                binding.rlLeaveHistory.setVisibility(View.GONE);
            } else {
                binding.tvDialogTitle.setText("Leave History");
                binding.btnSubmit.setVisibility(View.GONE);
                binding.rlApplyLeaveDetail.setVisibility(View.GONE);
                binding.rlLeaveHistory.setVisibility(View.VISIBLE);
            }

            binding.radioBFullday.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    binding.radioHalfDay.setChecked(false);
                    binding.radioBFullday.setChecked(true);
                    binding.tvFromDateInfo.setText("Date From");
                    binding.rlToDateInfo.setEnabled(true);
                    binding.tvFromDate.setText("");
                    binding.tvToDate.setText("");
                    binding.tvTodatePlaceholder.setTextColor(ContextCompat.getColor(context, R.color.black));
                }
            });

            binding.radioHalfDay.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    binding.radioHalfDay.setChecked(true);
                    binding.radioBFullday.setChecked(false);
                    binding.tvFromDateInfo.setText("Select Date");
                    binding.rlToDateInfo.setEnabled(false);
                    binding.tvFromDate.setText("");
                    binding.tvToDate.setText("");
                    binding.tvTodatePlaceholder.setTextColor(ContextCompat.getColor(context, R.color.gray));
                }
            });
            binding.btnSubmit.setOnClickListener(v -> {
                if (tbameSearch == null && binding.tvEmpCode.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code");
                } else if (!binding.radioBFullday.isChecked() && !binding.radioHalfDay.isChecked()) {
                    AlertandMessages.showToastMsg(context, "Please Select Leave Type(Full/Half day)");
                } else if (!binding.radioHalfDay.isChecked() && binding.radioBFullday.isChecked() && binding.tvFromDate.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Select Date From");
                } else if (!binding.radioHalfDay.isChecked() && binding.radioBFullday.isChecked() && binding.tvToDate.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Select Date to");
                } else if (!binding.radioBFullday.isChecked() && binding.radioHalfDay.isChecked() && binding.tvFromDate.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Select Date");
                } else if (Objects.requireNonNull(binding.edtapplyForleaveReason.getText()).toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Enter Reason");
                } else {
                    if (CommonFunctions.checkNetIsAvailable(context)) {
                        submitLeaveRequest(tbameSearch.getEmpId().toString(),
                                binding.radioBFullday.isChecked() ? binding.radioBFullday.getText().toString()
                                        : binding.radioHalfDay.getText().toString(),
                                binding.tvFromDate.getText().toString(), binding.tvToDate.getText().toString(),
                                binding.edtapplyForleaveReason.getText().toString());
                    } else {
                        AlertandMessages.showToastMsg(context, getString(R.string.nonetwork));
                    }
                }
            });
        }
    }

    private void submitLeaveRequest(String empId, String leaveType, String date_from, String date_to, String leaveReason) {
        ProgressDialog pd = null;
        try {
            pd = new ProgressDialog(context);
            pd.setTitle("Applying Leave Request");
            pd.setMessage("Please wait.....");
            pd.show();
            JSONObject json = new JSONObject().put("EmpId", empId)
                    .put("LeaveType", leaveType).put("FromDate", date_from).put("ToDate", leaveType.equals("Half Day") ? date_from : date_to)
                    .put("Reason", leaveReason).put("UserId", "");
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), json.toString());
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build()).addConverterFactory(GsonConverterFactory.create()).build();
            ProgressDialog finalPd = pd;
            adapter.create(PostApi.class).LeaveRequest(jsonData).enqueue(new Callback<String>() {
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                    String responseBody = response.body();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body();
                            assert data != null;
                            if (!data.equals("") && !data.contains("No Data")) {
                                Common common = new Gson().fromJson(data, Common.class);
                                if (common != null && common.getLeaveRequest().size() > 0) {
                                    assert common.getLeaveRequest().get(0).getResult() != null;
                                    if (common.getLeaveRequest().get(0).getResult().equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                        if (finalPd.isShowing()) finalPd.dismiss();
                                        showAlert(customDialogLeave, "Leave request applied successfully.");
                                    } else {
                                        if (finalPd.isShowing()) finalPd.dismiss();
                                        showAlert(customDialogLeave, common.getLeaveRequest().get(0).getResult());
                                    }
                                } else {
                                    if (finalPd.isShowing()) finalPd.dismiss();
                                    AlertandMessages.showToastMsg(context, getString(R.string.something_went_wrong));
                                }
                            } else {
                                if (finalPd.isShowing()) finalPd.dismiss();
                                AlertandMessages.showToastMsg(context, getString(R.string.something_went_wrong));
                            }
                            if (finalPd.isShowing()) finalPd.dismiss();
                        } catch (Exception e) {
                            if (finalPd.isShowing()) finalPd.dismiss();
                            AlertandMessages.showToastMsg(context, "Error in data.Please try again...");
                        }
                    } else {
                        if (finalPd.isShowing()) finalPd.dismiss();
                        AlertandMessages.showToastMsg(context, "Error in Data,Please try again...");
                    }
                }

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                    if (finalPd.isShowing()) finalPd.dismiss();
                    AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE);
                }
            });
        } catch (Exception ignored) {
            if (pd != null && pd.isShowing()) pd.dismiss();
        }

    }

    private void showAlert(CustomDialogLeaveApply customDialogLeave, String str) {
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(getString(R.string.parinaam));
            builder.setMessage(str).setCancelable(false)
                    .setPositiveButton(android.R.string.ok, (dialog, id) -> {
                        if (str.equals("Leave request applied successfully.")) {
                            if (leaveSpin != null) leaveSpin.setSelection(0);
                            if (customDialogLeave != null) customDialogLeave.cancel();
                        } else dialog.dismiss();
                    });
            AlertDialog alert = builder.create();
            alert.show();
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    private void getLeaveHistory(DialogApplyLeaveBinding binding) {
        ProgressDialog pd = null;
        try {
            pd = new ProgressDialog(context);
            pd.setTitle("Processing");
            pd.setMessage("Please wait.....");
            pd.show();
            JSONObject json = new JSONObject().put("Downloadtype", "TBAME_LeaveHistory")
                    .put("Username", "").put("Param1", Objects.requireNonNull(binding.etEmployeeCodeforHistory.getText()).toString()).put("Param2", "");
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), json.toString());
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build()).addConverterFactory(GsonConverterFactory.create()).build();
            ProgressDialog finalPd = pd;
            adapter.create(PostApi.class).getDownloadAll(jsonData).enqueue(new Callback<String>() {
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                    String responseBody = response.body();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body();
                            assert data != null;
                            if (!data.equals("") && !data.contains("No Data")) {
                                Common common = new Gson().fromJson(data, Common.class);
                                if (common != null && !common.getTBAMELeaveHistory().isEmpty()) {
                                    runOnUiThread(() -> {
                                        binding.tvEmpNameHistory.setText(CommonFunctions.capitalizeFirstLetter(common.getTBAMELeaveHistory().get(0).getName()));
                                        binding.tvEmpDesignationHistory.setText(common.getTBAMELeaveHistory().get(0).getDesignation());
                                        binding.tvEmpCodeHistory.setText(common.getTBAMELeaveHistory().get(0).getEmpCode());
                                        binding.recyclerLeaveDetail.setAdapter(new LeaveDetailAdapter(context, common.getTBAMELeaveHistory()));
                                        binding.recyclerLeaveDetail.setLayoutManager(new LinearLayoutManager(context));
                                        binding.rlLeaveDetailItem.setVisibility(View.VISIBLE);
                                    });
                                }
                            } else {
                                runOnUiThread(() -> {
                                    binding.tvEmpNameHistory.setText("");
                                    binding.tvEmpCodeHistory.setText("");
                                    binding.tvEmpDesignationHistory.setText("");
                                    binding.rlLeaveDetailItem.setVisibility(View.GONE);
                                });
                                AlertandMessages.showToastMsg(context, "No Leave history found for this employee . Please check Employee code and re-sync");
                            }
                            if (finalPd.isShowing()) finalPd.dismiss();
                        } catch (Exception e) {
                            runOnUiThread(() -> {
                                binding.tvEmpNameHistory.setText("");
                                binding.tvEmpCodeHistory.setText("");
                                binding.tvEmpDesignationHistory.setText("");
                                binding.rlLeaveDetailItem.setVisibility(View.GONE);
                            });
                            if (finalPd.isShowing()) finalPd.dismiss();
                            AlertandMessages.showAlert((Activity) context, "Error in Leave history data.", true);
                        }
                    } else {
                        runOnUiThread(() -> {
                            binding.tvEmpNameHistory.setText("");
                            binding.tvEmpCodeHistory.setText("");
                            binding.tvEmpDesignationHistory.setText("");
                            binding.rlLeaveDetailItem.setVisibility(View.GONE);
                        });
                        if (finalPd.isShowing()) finalPd.dismiss();
                        AlertandMessages.showAlert((Activity) context, "Error in downloading Data,Please try again... ", true);
                    }
                }

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                    runOnUiThread(() -> {
                        binding.tvEmpNameHistory.setText("");
                        binding.tvEmpCodeHistory.setText("");
                        binding.tvEmpDesignationHistory.setText("");
                        binding.rlLeaveDetailItem.setVisibility(View.GONE);
                    });
                    if (finalPd.isShowing()) finalPd.dismiss();
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE, true);
                }
            });
        } catch (Exception ignored) {
            if (pd != null && pd.isShowing()) pd.dismiss();
        }
    }

    private void getEmployeeDetails(String empId, TextView tvEmpName, TextView tvEmpId, TextView empDesignation) {
        ProgressDialog pd = null;
        try {
            pd = new ProgressDialog(context);
            pd.setTitle("Processing");
            pd.setMessage("Please wait.....");
            pd.show();
            JSONObject json = new JSONObject().put("Downloadtype", "TBAME_Search").put("Username", "").put("Param1", empId)
                    .put("Param2", "");
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), json.toString());
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build()).addConverterFactory(GsonConverterFactory.create()).build();
            ProgressDialog finalPd = pd;
            adapter.create(PostApi.class).getDownloadAll(jsonData).enqueue(new Callback<String>() {
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                    String responseBody = response.body();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body();
                            assert data != null;
                            if (!data.equals("") && !data.contains("No Data")) {
                                Common common = new Gson().fromJson(data, Common.class);
                                if (common != null && common.getTBAMESearch().size() > 0) {
                                    tbameSearch = common.getTBAMESearch().get(0);
                                    runOnUiThread(() -> {
                                        tvEmpName.setText(common.getTBAMESearch().get(0).getName());
                                        tvEmpId.setText(common.getTBAMESearch().get(0).getEmpCode());
                                        empDesignation.setText(common.getTBAMESearch().get(0).getDesignation());
                                    });
                                } else {
                                    tbameSearch = null;
                                    runOnUiThread(() -> {
                                        tvEmpName.setText("");
                                        tvEmpId.setText("");
                                        empDesignation.setText("");
                                    });
                                    AlertandMessages.showToastMsg(context, "Employee Detail not available. Please check Employee/Legacy code and re-sync");
                                }
                            } else {
                                tbameSearch = null;
                                runOnUiThread(() -> {
                                    tvEmpName.setText("");
                                    tvEmpId.setText("");
                                    empDesignation.setText("");
                                });
                                AlertandMessages.showToastMsg(context, "Employee Detail not available. Please check Employee/Legacy code and re-sync");
                            }
                            if (finalPd.isShowing()) finalPd.dismiss();
                        } catch (Exception e) {
                            tbameSearch = null;
                            runOnUiThread(() -> {
                                tvEmpName.setText("");
                                tvEmpId.setText("");
                                empDesignation.setText("");
                            });
                            if (finalPd.isShowing()) finalPd.dismiss();
                            AlertandMessages.showToastMsg(context, "Error in data. " + e.getMessage());
                        }
                    } else {
                        tbameSearch = null;
                        runOnUiThread(() -> {
                            tvEmpName.setText("");
                            tvEmpId.setText("");
                            empDesignation.setText("");
                        });
                        if (finalPd.isShowing()) finalPd.dismiss();
                        AlertandMessages.showToastMsg(context, "Error in downloading Data,Please try again... ");
                    }
                }

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                    tbameSearch = null;
                    runOnUiThread(() -> {
                        tvEmpName.setText("");
                        tvEmpId.setText("");
                        empDesignation.setText("");
                    });
                    if (finalPd.isShowing()) finalPd.dismiss();
                    AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE);
                }
            });
        } catch (Exception ignored) {
            if (pd != null && pd.isShowing()) pd.dismiss();
        }
    }
}
