package com.cygnusa.hyperm;

import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

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

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.appupdater.AppUpdater;
import com.cygnusa.hyperm.dbadapters.CommonDBHelper;
import com.cygnusa.hyperm.dbadapters.CustomerDetailsAdapter;
import com.cygnusa.hyperm.dbadapters.TableConstants;
import com.cygnusa.hyperm.library.AppUtils;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.CommonMethods;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.StorePreference;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.AppVersion;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.GetAllCustomerDetailsResponse;
import com.cygnusa.hyperm.wrappers.GetAllSalutationModel;
import com.cygnusa.hyperm.wrappers.ModelData;
import com.cygnusa.hyperm.wrappers.SendAllCustomerData;
import com.cygnusa.hyperm.wrappers.SendAllExploreDetailsModel;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ProductExploreDetailsActivity extends AppCompatActivity implements View.OnClickListener {
    Context context;
    private List<String> prefixDetailsSpinnerArray;
    Spinner spnPrefix;
    DisplayMetrics dm;
    MediaController media_Controller;
    private String ageRange = "";
    private EditText edtFirstName, edtLastName, edtMobileNumber, edtEmail;
    private TextView txtAgeFirst, txtAgeSecond, txtAgeThird, txtAgeFour, txtAgeFive;
    ApiService restService;
    ArrayAdapter<String> mGroupAdapter;
    SendAllExploreDetailsModel detailsModel;
    StorePreference storePreference;
    boolean doubleBackToExitPressedOnce = false;
    private TransparentProgressDialog progressDialog;
    private String currentTime = "";
    List<SendAllCustomerData> getAllOfflineData = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_explore_details);
        initViews();
        // this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        AppUpdater appUpdater = new AppUpdater(this);
        appUpdater.start();
        detailsModel = new SendAllExploreDetailsModel();
        if (CommonMethods.isNetworkAvailable(this)) {
            getAllSalutation();
            sendOfflineDataToServer();
        } else {
            getLocal();
        }
//        checkPermission();
    }

    public boolean validateEmailID(String str) {
        return str.contains("@") && str.lastIndexOf(".") != -1;
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            ArrayList<String> listPermissionsNeeded = new ArrayList<>();
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_DENIED) {
                listPermissionsNeeded
                        .add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
                listPermissionsNeeded
                        .add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
            }

            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(this, listPermissionsNeeded
                        .toArray(new String[listPermissionsNeeded.size()]), 1);
            } else {
              //  checkAppVersion();
            }
        } else {
            //checkAppVersion();
        }
    }

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

        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
           // checkAppVersion();
        }
    }

    private void checkAppVersion() {
        if (new UtilService().isNetworkAvailable(ProductExploreDetailsActivity.this)) {
            try {
                String url = GlobalData.APP_URL + "com.cygnusa.hyperm&deviceid=1";
                restService.getAppVersion(url).enqueue(new Callback<AppVersion>() {
                    @Override
                    public void onResponse(Call<AppVersion> call, Response<AppVersion> response) {
                        if (response.isSuccessful()) {
                            if (response.body() != null && Objects.requireNonNull(response.body())
                                    .getCont().trim().equalsIgnoreCase("success")) {
                                int versionCode = AppUtils.getVersionCode(ProductExploreDetailsActivity.this);
                                int iapkCode = Integer.parseInt(Objects.requireNonNull(response.body()).getVersioncode().trim());
                                if (iapkCode > versionCode) {
                                    showDialog(ProductExploreDetailsActivity.this, Objects.requireNonNull(response.body()).getUrl().getAndroid(), iapkCode);
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<AppVersion> call, Throwable t) {

                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private void showDialog(Context context, final String apkUrl, final int apkCode) {
        File f = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null), ".HYPERM");
        if (!f.exists()) {
            f.mkdirs();
        }

        File f1 = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null) + "/" + ".HYPERM", "Apk");
        if (!f1.exists()) {
            f1.mkdirs();
        }

        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ProductExploreDetailsActivity.this);
        builder.setMessage("New update for HYPER-M App is available")
                .setPositiveButton(context.getResources().getString(R.string.alert_update),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                downloadFile(apkUrl, apkCode);
                            }
                        }).setNegativeButton("Cancel", null);

        android.app.AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private void downloadFile(String url, int apkCode) {
        getApplication().registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        DownloadManager mgr = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Uri downloadUri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(
                downloadUri);
        request.setAllowedNetworkTypes(
                DownloadManager.Request.NETWORK_WIFI
                        | DownloadManager.Request.NETWORK_MOBILE)
                .setAllowedOverRoaming(false).setTitle("HYPER-M")
                .setDescription("Downloading...")
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                .setDestinationInExternalPublicDir("/.HYPERM/Apk", "hyperm_v_" + apkCode + ".apk");
        assert mgr != null;
        mgr.enqueue(request);
    }

    private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {
            try {
                if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
                    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                    String filePath = getDownloadedFilePath(ctxt, downloadId);
                    Intent intent1 = new Intent(Intent.ACTION_VIEW);
                    intent1.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent1);
                    finish();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            ctxt.unregisterReceiver(this);
        }
    };

    private String getDownloadedFilePath(Context context, long downloadId) {
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        String result = "";
        Cursor c = null;
        try {
            DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            assert downloadManager != null;
            c = downloadManager.query(query);
            if (c != null && c.moveToFirst()) {
                int fileUriIdx = c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
                String fileUri = c.getString(fileUriIdx);
                if (fileUri != null) {
                    File mFile = new File(Objects.requireNonNull(Uri.parse(fileUri).getPath()));
                    result = mFile.getAbsolutePath();
                }
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return result;
    }

    private void getLocal() {
        SharedPreferences pref = Objects.requireNonNull(ProductExploreDetailsActivity.this).getSharedPreferences("PRODUCT_MODULE", Context.MODE_PRIVATE);
        if (pref.getString("SALUTATION_" + storePreference.getStringValue(GlobalData.SALUTATION_MODEL), null) != null) {
            Gson gson = new Gson();
            prefixDetailsSpinnerArray = gson.fromJson(
                    pref.getString("SALUTATION_" + storePreference.getStringValue(GlobalData.SALUTATION_MODEL), null),
                    new TypeToken<List<String>>() {
                    }.getType());
            if (prefixDetailsSpinnerArray != null) {
                mGroupAdapter = new ArrayAdapter<>(context, R.layout.spinner_text_left, R.id.spinner_text, prefixDetailsSpinnerArray);
                spnPrefix.setAdapter(mGroupAdapter);
            }
        } else {
            Toast.makeText(ProductExploreDetailsActivity.this, "No data found", Toast.LENGTH_SHORT).show();
        }
    }

    private void getAllSalutation() {
        restService.getAllSaltuation().enqueue(new Callback<GetAllSalutationModel>() {
            @Override
            public void onResponse(Call<GetAllSalutationModel> call, Response<GetAllSalutationModel> response) {
                if (response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferences pref = Objects.requireNonNull(ProductExploreDetailsActivity.this).getSharedPreferences("PRODUCT_MODULE", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = pref.edit();
                        prefixDetailsSpinnerArray = response.body().getData();
                        if (prefixDetailsSpinnerArray.size() > 0) {
                            Gson gson = new Gson();
                            JsonElement jsonElement = gson.toJsonTree(
                                    prefixDetailsSpinnerArray, new TypeToken<List<String>>() {
                                    }.getType());
                            editor.putString("SALUTATION_" + storePreference.getStringValue(GlobalData.SALUTATION_MODEL),
                                    jsonElement.toString()).apply();

                            mGroupAdapter = new ArrayAdapter<>(context, R.layout.spinner_text_left, R.id.spinner_text, prefixDetailsSpinnerArray);
                            spnPrefix.setAdapter(mGroupAdapter);
                        } else {
                            getLocal();
                        }
                    } else if (response.body() != null && response.body().getStatus() == 401) {
                        GlobalData.canLogout = true;
                        startActivity(new Intent(getBaseContext(), LoginActivity.class));
                        finish();
                    } else if (response.errorBody() != null) {
                        Gson gson = new Gson();
                        ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                        GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                        if (message.getStatus() == 401) {
                            GlobalData.canLogout = true;
                            startActivity(new Intent(getBaseContext(), LoginActivity.class));
                            finish();
                        }
                    } else {
                        prefixDetailsSpinnerArray.add("-");
                        mGroupAdapter = new ArrayAdapter<>(context, R.layout.spinner_text_left, R.id.spinner_text, prefixDetailsSpinnerArray);
                        spnPrefix.setAdapter(mGroupAdapter);
                    }
                }
            }

            @Override
            public void onFailure(Call<GetAllSalutationModel> call, Throwable t) {
                getLocal();
            }
        });
    }

    private void initViews() {
        context = this;
        spnPrefix = findViewById(R.id.spn_select_from);
        prefixDetailsSpinnerArray = new ArrayList<>();
        LinearLayout llout_get_started = findViewById(R.id.llout_get_started);
        Button btn_get_started = findViewById(R.id.btn_get_started);
        btn_get_started.setOnClickListener(this);
        llout_get_started.setOnClickListener(this);
        storePreference = new StorePreference(this);

        edtEmail = findViewById(R.id.edtEmail);
        edtFirstName = findViewById(R.id.edtFirstName);
        edtLastName = findViewById(R.id.edt_last_name);
        edtMobileNumber = findViewById(R.id.edtMobNumer);
        //  hideKeyboard(this);
//        edtMobileNumber.setShowSoftInputOnFocus(false);
//        edtEmail.setShowSoftInputOnFocus(false);
//        edtFirstName.setShowSoftInputOnFocus(false);
//        edtLastName.setShowSoftInputOnFocus(false);

        txtAgeFirst = findViewById(R.id.txtAgeFirst);
        txtAgeSecond = findViewById(R.id.txtAgeSecond);
        txtAgeThird = findViewById(R.id.txtAgeThird);
        txtAgeFour = findViewById(R.id.txtAgeFour);
        txtAgeFive = findViewById(R.id.txtAgeFive);
        txtAgeFive.setOnClickListener(this);
        txtAgeFour.setOnClickListener(this);
        txtAgeThird.setOnClickListener(this);
        txtAgeSecond.setOnClickListener(this);
        txtAgeFirst.setOnClickListener(this);
        progressDialog = new TransparentProgressDialog(ProductExploreDetailsActivity.this);
        LinearLayout whole_layout = findViewById(R.id.whole_lin_layout);
        whole_layout.setOnClickListener(this);
        restService = ((MainApplication) getApplication()).getClient();
    }

    @Override
    public void onBackPressed() {
        if (doubleBackToExitPressedOnce) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                finishAffinity();
            } else {
                System.exit(0);
                finish();
            }
            return;
        }
        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Please click again to exit", Toast.LENGTH_SHORT).show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);

    }

    private void loadVideo() {
        media_Controller = new MediaController(this);
        dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int height = dm.heightPixels;
        int width = dm.widthPixels;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llout_get_started:
                currentTime = String.valueOf(System.currentTimeMillis());
                currentTime = GlobalData.user.getData().getEmp_code() + currentTime;
                storePreference.setString(GlobalData.CURRENTTIME, currentTime);
                sendOfflineDataToServer();
                fieldValidation();
                break;
            case R.id.whole_lin_layout:
//                hideKeyboard(ProductExploreDetailsActivity.this);
                break;
            case R.id.btn_get_started:
                currentTime = String.valueOf(System.currentTimeMillis());
                currentTime = GlobalData.user.getData().getEmp_code() + currentTime;
                storePreference.setString(GlobalData.CURRENTTIME, currentTime);
                sendOfflineDataToServer();
                fieldValidation();
                break;
            case R.id.txtAgeFirst:
                clickSelectedAgeRange(txtAgeFirst, txtAgeSecond, txtAgeThird, txtAgeFour, txtAgeFive);
                ageRange = txtAgeFirst.getText().toString();
                break;
            case R.id.txtAgeSecond:
                clickSelectedAgeRange(txtAgeSecond, txtAgeFirst, txtAgeThird, txtAgeFour, txtAgeFive);
                ageRange = txtAgeSecond.getText().toString();
                break;
            case R.id.txtAgeThird:
                clickSelectedAgeRange(txtAgeThird, txtAgeFirst, txtAgeSecond, txtAgeFour, txtAgeFive);
                ageRange = txtAgeThird.getText().toString();
                break;
            case R.id.txtAgeFour:
                clickSelectedAgeRange(txtAgeFour, txtAgeFirst, txtAgeSecond, txtAgeThird, txtAgeFive);
                ageRange = txtAgeFour.getText().toString();
                break;
            case R.id.txtAgeFive:
                clickSelectedAgeRange(txtAgeFive, txtAgeFirst, txtAgeSecond, txtAgeThird, txtAgeFour);
                ageRange = txtAgeFive.getText().toString();
                break;
            default:
        }
    }

    private void hideKeyboard(Activity activity) {
        InputMethodManager inputMethodManager =
                (InputMethodManager) this.getSystemService(
                        Activity.INPUT_METHOD_SERVICE);
        Objects.requireNonNull(inputMethodManager).hideSoftInputFromWindow(
                Objects.requireNonNull(activity.getCurrentFocus()).getWindowToken(), 0);
    }

    private void fieldValidation() {
        if (edtFirstName.getText().toString().equalsIgnoreCase("")) {
            CommonMethods.showToast(context, "Enter your name.").show();
        } else if (edtMobileNumber.getText().toString().equalsIgnoreCase("")) {
            CommonMethods.showToast(context, "Enter your mobile number.").show();
        } else if (!Patterns.PHONE.matcher(edtMobileNumber.getText().toString()).matches()) {
            CommonMethods.showToast(context, "Enter your valid mobile number.").show();
        } else if (edtMobileNumber.getText().length() < 10) {
            CommonMethods.showToast(context, "Enter your valid mobile number.").show();
        }
//        else if (edtEmail.getText().toString().equalsIgnoreCase("")) {
//            GlobalData.showToast(this, "Enter E-mail address", Toast.LENGTH_LONG).show();
//        }
//        else if(!validateEmailID(edtEmail.getText().toString())){
////            GlobalData.showToast(this, "Please enter your valid email id", Toast.LENGTH_LONG).show();
////        }
        else if (ageRange.equalsIgnoreCase("")) {
            CommonMethods.showToast(context, "Select age range.").show();
        } else {
            storePreference.setString(GlobalData.PRODUCT_NAME, edtFirstName.getText().toString().trim());
            if (CommonMethods.isNetworkAvailable(this)) {
                sendOfflineDataToServer();
                sendDetailsToServer();
            } else {
                insertDetailsToServer();
            }
        }
    }

    public void hideSoftKeyboard() {
        if (getCurrentFocus() != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            Objects.requireNonNull(inputMethodManager).hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    private void sendOfflineDataToServer() {
        SendAllExploreDetailsModel detailsModel = new SendAllExploreDetailsModel();
        CustomerDetailsAdapter customerDetailsAdapter = new CustomerDetailsAdapter(ProductExploreDetailsActivity.this);
        getAllOfflineData = customerDetailsAdapter.getAllDataFromDB();
        List<SendAllCustomerData> allCustomerData = new ArrayList<>();
        if (getAllOfflineData != null && getAllOfflineData.size() > 0) {
            detailsModel.setEmp_code(GlobalData.user.getData().getEmp_code());
            detailsModel.setSmpin(GlobalData.user.getData().getSmpin());
            detailsModel.setMobile("");
            for (int i = 0; i < getAllOfflineData.size(); i++) {
                Log.e("Name", getAllOfflineData.get(i).getFirstname());
                SendAllCustomerData customerData = new SendAllCustomerData();
                customerData.setSalutation(getAllOfflineData.get(i).getSalutation());
                customerData.setAge(getAllOfflineData.get(i).getAge());
                customerData.setEmail(getAllOfflineData.get(i).getEmail());
                customerData.setFirstname(getAllOfflineData.get(i).getFirstname());
                customerData.setLastname(getAllOfflineData.get(i).getLastname());
                customerData.setMobile(getAllOfflineData.get(i).getMobile());
                customerData.setUid(getAllOfflineData.get(i).getUid());
                allCustomerData.add(customerData);
            }
            if (allCustomerData.size() > 0)
                detailsModel.setCustomerData(allCustomerData);
            restService.sendAllExploreDetails(detailsModel).enqueue(new Callback<GetAllCustomerDetailsResponse>() {
                @Override
                public void onResponse(Call<GetAllCustomerDetailsResponse> call, Response<GetAllCustomerDetailsResponse> response) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    if (response.body() != null) {
                        if (response.body().getStatus() == 200) {
                            CommonDBHelper.getInstance(getApplicationContext()).deleteTableValues(TableConstants.TABLE_CUSTOMER_DETAILS);
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                        } else {
                            CommonMethods.showToast(context, response.body().getMessage()).show();
                        }
                    }
                }

                @Override
                public void onFailure(Call<GetAllCustomerDetailsResponse> call, Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                }
            });
        }
    }

    public static void hideKeyboardFrom(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        Objects.requireNonNull(imm).hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    private void insertDetailsToServer() {
        CustomerDetailsAdapter customerDetailsAdapter = new CustomerDetailsAdapter(ProductExploreDetailsActivity.this);
        if (!CustomerDetailsAdapter.checkRecordExists(edtMobileNumber.getText().toString())) {
            customerDetailsAdapter.insertLoginDetails(currentTime, spnPrefix.getSelectedItem().toString(), edtFirstName.getText().toString(), edtMobileNumber.getText().toString(), edtEmail.getText().toString(), ageRange);
            startActivity(new Intent(ProductExploreDetailsActivity.this, ProductHomeActivity.class));
        } else {
            startActivity(new Intent(ProductExploreDetailsActivity.this, ProductHomeActivity.class));
        }
    }

    private void sendDetailsToServer() {
        progressDialog.show();
        restService.sendAllExploreDetails(buildConfigData()).enqueue(new Callback<GetAllCustomerDetailsResponse>() {
            @Override
            public void onResponse(Call<GetAllCustomerDetailsResponse> call, Response<GetAllCustomerDetailsResponse> response) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        storePreference.setString(GlobalData.DETAIL_NAME, edtFirstName.getText().toString());
                        storePreference.setString(GlobalData.DETAIL_EMAIL, edtEmail.getText().toString());
                        storePreference.setString(GlobalData.DETAIL_MOBILE, edtMobileNumber.getText().toString());
                        if (response.body().getIs_exist() == 1) {
                            openPopup(response.body().getModel_data());
                        } else {
                            startActivity(new Intent(ProductExploreDetailsActivity.this, ProductHomeActivity.class));
                        }
                    } else if (response.errorBody() != null) {
                        Gson gson = new Gson();
                        ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                        GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                    } else {
                        CommonMethods.showToast(context, response.body().getMessage()).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<GetAllCustomerDetailsResponse> call, Throwable t) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }
        });

    }

    public void openPopup(ModelData data) {
        final Dialog aDialog = new Dialog(this);
        aDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        aDialog.setContentView(R.layout.model_view_popup);
        aDialog.setCancelable(true);
        TextView model_name = aDialog.findViewById(R.id.model_name);
        TextView description = aDialog.findViewById(R.id.description);
        model_name.setText(data.getTitle());
        description.setText(String.format("%s %s", getResources().getString(R.string.msg_text), data.getModel_name().trim()));
        aDialog.show();
        ImageView img_model;
        img_model = aDialog.findViewById(R.id.img_close);
        Glide.with(context).load(data.getModel_image_url())
                .thumbnail(Glide.with(context).load(R.drawable.gif_loader))
                .apply(new RequestOptions().fitCenter().diskCacheStrategy(DiskCacheStrategy.ALL)
                        .placeholder(R.drawable.placeholder)).into(img_model);
        img_model.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                aDialog.dismiss();
            }
        });
        Button btnYes = aDialog.findViewById(R.id.btn_continue);
        btnYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                aDialog.dismiss();
                startActivity(new Intent(ProductExploreDetailsActivity.this, ProductHomeActivity.class));
                finish();

            }
        });
    }

    private SendAllExploreDetailsModel buildConfigData() {
        SendAllExploreDetailsModel detailsModel = new SendAllExploreDetailsModel();
        detailsModel.setEmp_code(GlobalData.user.getData().getEmp_code());
        detailsModel.setSmpin(GlobalData.user.getData().getSmpin());
        detailsModel.setMobile(edtMobileNumber.getText().toString().trim());
        List<SendAllCustomerData> allCustomerData = new ArrayList<>();
        SendAllCustomerData customerData = new SendAllCustomerData();
        customerData.setSalutation(spnPrefix.getSelectedItem().toString());
        customerData.setAge(ageRange);
        customerData.setEmail(edtEmail.getText().toString());
        customerData.setFirstname(edtFirstName.getText().toString());
        customerData.setLastname(edtLastName.getText().toString());
        customerData.setMobile(edtMobileNumber.getText().toString());
        customerData.setUid(currentTime);
        allCustomerData.add(customerData);
        detailsModel.setCustomerData(allCustomerData);
        return detailsModel;
    }

    private void clickSelectedAgeRange(TextView txtAgeFirst, TextView txtAgeSecond, TextView txtAgeThird, TextView txtAgeFour, TextView txtAgeFive) {
        txtAgeFirst.setBackground(ContextCompat.getDrawable(context, R.drawable.edt_border));
        txtAgeSecond.setBackground(ContextCompat.getDrawable(context, R.drawable.edt_unselected_border));
        txtAgeThird.setBackground(ContextCompat.getDrawable(context, R.drawable.edt_unselected_border));
        txtAgeFour.setBackground(ContextCompat.getDrawable(context, R.drawable.edt_unselected_border));
        txtAgeFive.setBackground(ContextCompat.getDrawable(context, R.drawable.edt_unselected_border));
    }
}
