package com.cpm.lorealbaMabeline.checkout;

import static com.cpm.lorealbaMabeline.constant.CommonFunctions.getCurrentTime;
import static com.cpm.lorealbaMabeline.dailyactivity.StoreImageActivity.convertBitmap;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.InputFilter;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.constant.AlertandMessages;
import com.cpm.lorealbaMabeline.constant.CommonFunctions;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.databinding.ActivityBacheckoutBinding;
import com.cpm.lorealbaMabeline.databinding.ItemBacheckoutBinding;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;
import com.cpm.lorealbaMabeline.download.Downloader;
import com.cpm.lorealbaMabeline.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaMabeline.retrofit.UploadDataWithRetrofit;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.Priority;
import com.google.android.gms.location.SettingsClient;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.gson.JsonSyntaxException;

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

import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class BaCheckoutActivity extends AppCompatActivity {
    private String counter_Id, visit_date, username, _pathforcheck, _path, img_str = "", checkout_img_str = "";
    private double latitude = 0.0, logitude = 0.0;
    private SharedPreferences.Editor editor = null;
    private SharedPreferences preferences = null;
    private Lorealba_Database db;
    private boolean checkflag = true, clickFlag = false, onspinTouch = false;
    private JourneyPlan jcp_Object = null;
    private QuestionAdapter adapter = null;
    private ActivityBacheckoutBinding binding = null;
    private ArrayList<MasterCheckoutQuestion> questions = new ArrayList<>();
    private int _pos = -1;

    String blockCharacterSet = "[';:-+{('}<!>@=#$%^&*?)\"]";
    InputFilter filter = (source, start, end, dest, dstart, dend) -> {
        if (source != null && blockCharacterSet.contains(("" + source))) {
            return "";
        }
        return null;
    };

    private static final int REQUEST_LOCATION = 1;
    private FusedLocationProviderClient fusedLocationClient = null;
    private LocationCallback locationCallback = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBacheckoutBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        fusedLocationClient = LocationServices.
                getFusedLocationProviderClient(this);
        db = new Lorealba_Database(this);
        db.open();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (!CommonFunctions.isTablet(this)) {
            toolbar.setTitleTextAppearance(this, R.style.changestext_sizefor_mobile);
        }
        iduserinterface();
        showAlertOfLogout();
        setTitle("Checkout Selfie - " + username);
        binding.contentCheckout.imgCamSelfie.setOnClickListener(v -> {
            clickFlag = true;
            _pathforcheck = counter_Id + "-Checkout_Selfie_img_" + username + "_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(this) + _pathforcheck;
            if (CommonFunctions.isTablet(this)) {
                CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR);
            } else {
                CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_FRONT);
            }
        });
    }

    private void iduserinterface() {
        preferences = PrefHelper.getPrefs(this);
        editor = preferences.edit();
        counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        jcp_Object = db.getBIDfromJCP(username, counter_Id);
        Log.e("jcp_Object", "MID : " + jcp_Object.getMID().toString() + " BID : " + jcp_Object.getBID() + " UserId : " + username);
        callquestions();
        getLastLocation();
        binding.fab.setOnClickListener(v -> {
            CommonFunctions.dismissKeyboard(v);
            if (checkout_img_str.isEmpty()) {
                AlertandMessages.showToastMsg(v.getContext(), "Please click Selfie in front of counter at Checkout");
            } else if (validate()) {
                if (CommonFunctions.checkNetIsAvailable(v.getContext())) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext()).setTitle(R.string.parinaam).setMessage(R.string.title_activity_save_data).setCancelable(false).setPositiveButton(R.string.yes, (dialog, id) -> {
                        new BaCheckoutUpload(this).execute();
                        //upload service
                        Downloader.enqueueWork(v.getContext(), new Intent(v.getContext(),
                                Downloader.class).putExtra(CommonString.KEY_UPLOADIMAGE, "1"));
                    }).setNegativeButton(R.string.no, (dialog, id) -> dialog.cancel());
                    AlertDialog alert = builder.create();
                    alert.show();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        db.open();
        checkgpsEnableDevice();
    }

    private void checkgpsEnableDevice() {
        if (!hasGPSDevice(this)) {
            Toast.makeText(this, "Gps not Supported", Toast.LENGTH_SHORT).show();
        }
        final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(this)) {
            enableLocationSettings();
        } else {
            if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                hasGPSDevice(this);
            }
        }
    }

    private void enableLocationSettings() {
        LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, // priority
                5000                             // intervalMillis: 5 seconds
        ).setMinUpdateIntervalMillis(3000)       // fastest interval
                .build();
        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) this, REQUEST_LOCATION);
                } catch (IntentSender.SendIntentException sendEx) {
                    // Ignore the error.
                    sendEx.fillInStackTrace();
                }
            }
        });
    }

    private boolean hasGPSDevice(Context context) {
        final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (mgr == null) return false;
        final List<String> providers = mgr.getAllProviders();
        return providers.contains(LocationManager.GPS_PROVIDER);
    }

    private void getLastLocation() {
        if (fusedLocationClient == null) {
            fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        }

        // fastest interval
        LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000)
                .setMinUpdateIntervalMillis(3000) // fastest interval
                .build();
        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(@NonNull LocationResult locationResult) {
                for (Location location : locationResult.getLocations()) {
                    if (location != null) {
                        latitude = location.getLatitude();
                        logitude = location.getLongitude();
                        Log.d("Location", "Lat: " + latitude + ", Lng: " + logitude);
                    }
                }
            }
        };
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // Request permissions if not granted
            return;
        }
        fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
    }

    private void stopLocationUpdates() {
        if (fusedLocationClient != null && locationCallback != null) {
            fusedLocationClient.removeLocationUpdates(locationCallback);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopLocationUpdates();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            backPress();
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onBackPressed() {
        backPress();
    }

    private void backPress() {
        if (clickFlag) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", (dialog, id1) -> {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                this.finish();
            }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel());
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            this.finish();
        }
    }

    private void callquestions() {
        db.open();
        questions = db.getCheckoutQuestions(counter_Id, "", username);
        binding.contentCheckout.tvPrompt.setVisibility(questions != null && !questions.isEmpty() ? View.VISIBLE : View.GONE);
        binding.contentCheckout.recyclQuestionire.setVisibility(questions != null && !questions.isEmpty() ? View.VISIBLE : View.GONE);
        adapter = new QuestionAdapter(this, questions);
        binding.contentCheckout.recyclQuestionire.setAdapter(adapter);
        binding.contentCheckout.recyclQuestionire.setLayoutManager(new LinearLayoutManager(this));
    }

    private class QuestionAdapter extends RecyclerView.Adapter<QuestionAdapter.ViewHolder> {
        Context context;
        ArrayList<MasterCheckoutQuestion> listDataHeader;

        public QuestionAdapter(Context context, ArrayList<MasterCheckoutQuestion> listDataHeader) {
            this.context = context;
            this.listDataHeader = listDataHeader;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            ItemBacheckoutBinding itemBinding = ItemBacheckoutBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
            return new ViewHolder(itemBinding);
        }

        @SuppressLint({"SetTextI18n", "ClickableViewAccessibility"})
        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") final int pos) {
            final MasterCheckoutQuestion object = listDataHeader.get(pos);
            holder.item_binding.txtQuestion.setText(object.getQuestion());
            holder.item_binding.txtQuestion.setId(pos);

            if (object.getAns() != null && !object.getAns().isEmpty()) {
                holder.item_binding.spAuditAnswer.setAdapter(new AnswerSpinnerAdapter(context, R.layout.custom_spinner_item, object.getAns()));
                holder.item_binding.spAuditAnswer.setId(pos);
            }

            if (object.getQuestionType().equals("List Single Choice")) {
                holder.item_binding.rlSpin.setVisibility(View.VISIBLE);
                holder.item_binding.edtAnswer.setVisibility(View.GONE);
                holder.item_binding.rlSpin.setId(pos);
                holder.item_binding.edtAnswer.setId(pos);
            } else if (object.getQuestionType().equals("Number") || object.getQuestionType().equals("Text")) {
                holder.item_binding.rlSpin.setVisibility(View.GONE);
                holder.item_binding.edtAnswer.setVisibility(View.VISIBLE);
                holder.item_binding.rlSpin.setId(pos);
                holder.item_binding.edtAnswer.setId(pos);
                holder.item_binding.edtAnswer.setHint(object.getQuestion());
                holder.item_binding.edtAnswer.setInputType(object.getQuestionType().equals("Number") ? InputType.TYPE_CLASS_NUMBER : InputType.TYPE_CLASS_TEXT);
                holder.item_binding.edtAnswer.setTypeface(holder.item_binding.edtAnswer.getTypeface(), object.getQuestionType().equals("Number") ? Typeface.BOLD : Typeface.NORMAL);
                holder.item_binding.edtAnswer.setFilters(new InputFilter[]{filter, object.getQuestionType().equals("Number") ? new InputFilter.LengthFilter(object.getMaxLength()) : new InputFilter.LengthFilter(350)});
            }

            holder.item_binding.spAuditAnswer.setOnTouchListener((view, motionEvent) -> {
                onspinTouch = true;
                return false;
            });

            holder.item_binding.spAuditAnswer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (onspinTouch) {
                        if (position != 0) {
                            MasterCheckoutQuestion ans = object.getAns().get(position);
                            object.setCorrect_ans(ans.getAnswer());
                            object.setCorrect_ansId(ans.getAnswerId());
                            object.setImageAllow(ans.getImageAllow());
                            object.setImageAllowMandatory(ans.getImageAllowMandatory());
                            if (ans.getImageAllow()) {
                                holder.item_binding.rlAnsImg.setVisibility(View.VISIBLE);
                            } else {
                                holder.item_binding.rlAnsImg.setVisibility(View.GONE);
                                if (!object.getAnsImg().isEmpty()) {
                                    if (new File(CommonString.getImagesFolder(context) + object.getAnsImg()).exists()) {
                                        new File(CommonString.getImagesFolder(context) + object.getAnsImg()).delete();
                                    }
                                }
                                object.setAnsImg("");
                            }

                            holder.item_binding.ansImg.setImageResource(object.getImageAllow() && object.getImageAllowMandatory() ? R.mipmap.camera_star : R.mipmap.camera_bs);
                            holder.item_binding.ansImg.setId(pos);
                            holder.item_binding.rlAnsImg.setId(pos);
                        } else {
                            object.setAnsImg("");
                            object.setCorrect_ans("");
                            object.setCorrect_ansId(0);
                            object.setImageAllow(false);
                            object.setImageAllowMandatory(false);
                            holder.item_binding.rlAnsImg.setId(pos);
                            holder.item_binding.rlAnsImg.setVisibility(View.GONE);
                        }
                    }
                    onspinTouch = false;
                }

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

                }
            });

            holder.item_binding.edtAnswer.setOnFocusChangeListener((v, hasFocus) -> {
                if (!hasFocus) {
                    object.setCorrect_ansId(0);
                    object.setCorrect_ans(((EditText) v).getText().toString());
                }
            });

            holder.item_binding.edtAnswer.setText(object.getCorrect_ans());
            holder.item_binding.edtAnswer.setId(pos);

            if (object.getAns() != null && !object.getAns().isEmpty()) {
                for (int i = 0; i < object.getAns().size(); i++) {
                    if ((object.getQuestionType().equals("List Single Choice") && object.getAns().get(i).getAnswerId().toString().equals(object.getCorrect_ansId().toString()))) {
                        holder.item_binding.spAuditAnswer.setSelection(i);
                        break;
                    }
                }
            }

            holder.item_binding.questionImg.setOnClickListener(v -> {
                _pathforcheck = object.getQuestionId().toString() + "_" + counter_Id + "_CheckoutQuestionImg-" + visit_date.replace("/", "") + CommonFunctions.getCurrentTimeHHMMSS().replace(":", "") + ".jpg";
                _path = CommonString.getImagesFolder(context) + _pathforcheck;
                CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);
                _pos = pos;
            });

            holder.item_binding.ansImg.setOnClickListener(v -> {
                String ansId = object.getCorrect_ansId() != 0 ? object.getCorrect_ansId().toString() + "_" : "";
                _pathforcheck = object.getQuestionId().toString() + "_" + ansId + counter_Id + "_CheckoutAnsImg-" + visit_date.replace("/", "") + CommonFunctions.getCurrentTimeHHMMSS().replace(":", "") + ".jpg";
                _path = CommonString.getImagesFolder(context) + _pathforcheck;
                CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);
                _pos = pos;
            });

            if (!img_str.isEmpty()) {
                if (_pos == pos) {
                    if (img_str.contains("_CounterCheckoutImg-")) {
                        object.setQuestionImg(img_str);
                    } else {
                        object.setAnsImg(img_str);
                    }
                    img_str = "";
                    _pos = -1;
                }
            }

            holder.item_binding.rlQImg.setVisibility(object.getQuestionImageAllow() ? View.VISIBLE : View.GONE);
            holder.item_binding.rlQImg.setId(pos);
            holder.item_binding.questionImg.setImageResource(!object.getQuestionImg().isEmpty() ? R.mipmap.camera_bsd : object.getQuestionImageAllow()
                    && object.getQuestionImageMandatory() ? R.mipmap.camera_star : R.mipmap.camera_bs);
            holder.item_binding.questionImg.setId(pos);

            holder.item_binding.rlAnsImg.setVisibility(object.getImageAllow() ? View.VISIBLE : View.GONE);
            holder.item_binding.rlAnsImg.setId(pos);
            holder.item_binding.ansImg.setImageResource(!object.getAnsImg().isEmpty() ? R.mipmap.camera_bsd :
                    object.getImageAllow() && object.getImageAllowMandatory() ? R.mipmap.camera_star : R.mipmap.camera_bs);
            holder.item_binding.ansImg.setId(pos);

        }

        @Override
        public int getItemCount() {
            return listDataHeader.size();
        }

        private static class ViewHolder extends RecyclerView.ViewHolder {
            ItemBacheckoutBinding item_binding;

            private ViewHolder(@NonNull ItemBacheckoutBinding itemBacheckoutBinding) {
                super(itemBacheckoutBinding.getRoot());
                this.item_binding = itemBacheckoutBinding;
            }
        }
    }

    private static class AnswerSpinnerAdapter extends ArrayAdapter<MasterCheckoutQuestion> {
        List<MasterCheckoutQuestion> list;
        Context context;
        int resourceId;

        public AnswerSpinnerAdapter(Context context, int resourceId, ArrayList<MasterCheckoutQuestion> list) {
            super(context, resourceId, list);
            this.context = context;
            this.list = list;
            this.resourceId = resourceId;
        }

        @NonNull
        @SuppressLint("ViewHolder")
        @Override
        public View getView(int position, View convertView, @NonNull ViewGroup parent) {
            View view = convertView;
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            view = inflater.inflate(resourceId, parent, false);
            MasterCheckoutQuestion cm = list.get(position);
            TextView txt_spinner = (TextView) view.findViewById(R.id.tv_ans);
            txt_spinner.setGravity(Gravity.CENTER_VERTICAL);
            txt_spinner.setText(list.get(position).getAnswer());
            return view;
        }

        @Override
        public View getDropDownView(int position, View _convertView, @NonNull ViewGroup parent) {
            View view = _convertView;
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            view = inflater.inflate(resourceId, parent, false);
            MasterCheckoutQuestion cm = list.get(position);
            TextView txt_spinner = (TextView) view.findViewById(R.id.tv_ans);
            txt_spinner.setGravity(Gravity.CENTER_VERTICAL);
            txt_spinner.setText(cm.getAnswer());
            return view;
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("MakeMachine", "resultCode: " + resultCode);
        switch (resultCode) {
            case 0:
                Log.i("MakeMachine", "User cancelled");
                break;
            case -1:
                if (_pathforcheck != null && !_pathforcheck.isEmpty()) {
                    if (new File(CommonString.getImagesFolder(this) + _pathforcheck).exists()) {
                        Bitmap bmp = convertBitmap(CommonString.getImagesFolder(this) + _pathforcheck);
                        if (_pathforcheck.contains("-Checkout_Selfie_img_")) {
                            try {
                                binding.contentCheckout.imgSelfie.setImageBitmap(bmp);
                            } catch (OutOfMemoryError ex) {
                                CommonFunctions.setScaledImage(binding.contentCheckout.imgSelfie, CommonString.getImagesFolder(this) + _pathforcheck);
                            }
                            binding.contentCheckout.imgCamSelfie.setVisibility(View.GONE);
                            binding.contentCheckout.imgSelfie.setVisibility(View.VISIBLE);
                            checkout_img_str = _pathforcheck;
                        } else {
                            img_str = _pathforcheck;
                            if (adapter != null) adapter.notifyDataSetChanged();
                        }

                        _pathforcheck = "";
                    }
                }

                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @SuppressLint("NotifyDataSetChanged")
    private boolean validate() {
        checkflag = true;
        adapter.notifyDataSetChanged();
        if (questions != null && !questions.isEmpty()) {
            for (int a = 0; a < questions.size(); a++) {
                if (questions.get(a).getCorrect_ans().isEmpty()) {
                    AlertandMessages.showToastMsg(this, "Please " + (questions.get(a).getQuestionType().equals("List Single Choice") ? "Select an answer for the " + questions.get(a).getQuestion() : "provide an answer to the " + questions.get(a).getQuestion()));
                    checkflag = false;
                    break;
                } else if (questions.get(a).getQuestionImageAllow() && questions.get(a).getQuestionImageMandatory() && questions.get(a).getQuestionImg().isEmpty()) {
                    AlertandMessages.showToastMsg(this, "Please capture image of the " + questions.get(a).getQuestion());
                    checkflag = false;
                    break;
                } else if (questions.get(a).getImageAllow() && questions.get(a).getImageAllowMandatory() && questions.get(a).getAnsImg().isEmpty()) {
                    AlertandMessages.showToastMsg(this, "Please capture image of the " + questions.get(a).getQuestion());
                    checkflag = false;
                    break;
                }
            }
        }

        return checkflag;
    }


    @SuppressLint({"StaticFieldLeak", ""})
    private class BaCheckoutUpload extends AsyncTask<Void, Void, String> {
        private ProgressDialog loading = null;
        private boolean uploadflag;
        private String errormsg = "";
        private Context context;

        private BaCheckoutUpload(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(context, "Uploading Checkout Info", "Please wait...", false, true);
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                // uploading BaCheckoutUpload
                uploadflag = false;
                if (!checkout_img_str.isEmpty()) {
                    String jsonString2 = getString();
                    Log.e("jsonString2", jsonString2);
                    UploadDataWithRetrofit upload = new UploadDataWithRetrofit(context);
                    String result = upload.uploadDeviceTokenDetails(jsonString2, 420);
                    if (result.contains("1")) {
                        uploadflag = true;
                    } else if (result.equalsIgnoreCase(CommonString.MESSAGE_NO_RESPONSE_SERVER)) {
                        uploadflag = false;
                        throw new SocketTimeoutException();
                    } else if (result.equalsIgnoreCase(CommonString.MESSAGE_SOCKETEXCEPTION)) {
                        uploadflag = false;
                        throw new IOException();
                    } else if (result.equalsIgnoreCase(CommonString.KEY_FAILURE)) {
                        uploadflag = false;
                        throw new Exception();
                    }
                }
            } catch (IOException ex) {
                uploadflag = false;
                ex.fillInStackTrace();
                errormsg = CommonString.MESSAGE_INTERNET_NOT_AVALABLE;
            } catch (JsonSyntaxException ex) {
                uploadflag = false;
                ex.fillInStackTrace();
                errormsg = CommonString.MESSAGE_INVALID_JSON;
            } catch (Exception ex) {
                uploadflag = false;
                errormsg = CommonString.MESSAGE_EXCEPTION;
            }
            if (uploadflag) {
                return CommonString.KEY_SUCCESS;
            } else {
                return errormsg;
            }
        }

        private @NonNull String getString() throws JSONException {
            JSONArray array = new JSONArray();
            if (questions != null && !questions.isEmpty()) {
                JSONObject jsonObject = null;
                for (MasterCheckoutQuestion question : questions) {
                    jsonObject = new JSONObject();
                    jsonObject.put("QuestionId", question.getQuestionId());
                    jsonObject.put("QuestionType", question.getQuestionType());
                    jsonObject.put("AnswerId", question.getCorrect_ansId());
                    jsonObject.put("Answer", question.getCorrect_ans());
                    jsonObject.put("QuestionImg", question.getQuestionImg());
                    jsonObject.put("AnsImg", question.getAnsImg());
                    array.put(jsonObject);
                }
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("MID", jcp_Object.getMID());
            jsonObject.put("BID", jcp_Object.getBID());
            jsonObject.put("Latitude", latitude);
            jsonObject.put("Longitude", logitude);
            jsonObject.put("CheckoutImage", checkout_img_str);
            jsonObject.put("JsonQuestion", array.toString());
            jsonObject.put("UserId", username);
            return jsonObject.toString();
        }


        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result != null && result.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle(context.getString(R.string.parinaam));
                builder.setMessage("You have successfully checked out.").setCancelable(false)
                        .setPositiveButton(android.R.string.ok, (dialog_, id) -> {
                            runOnUiThread(() -> {
                                db.open();
                                db.updateCheckoutStatus(counter_Id, jcp_Object.getBID().toString(), username);
                                editor = preferences.edit();
                                editor.putBoolean(CommonString.KEY_IS_CHECKOUT_DONE + username + visit_date, true);
                                editor.apply();
                                finishAffinity();
                            });
                            dialog_.dismiss();
                        });
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                AlertandMessages.showAlert((Activity) context, getResources().getString(R.string.failure) + " : " + errormsg, true);
            }
            /// dismiss progress dialog
            if (loading != null && loading.isShowing()) loading.dismiss();
        }
    }

    private void showAlertOfLogout() {
        MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this, R.style.MyMaterialAlertDialog)
                .setTitle("Hi User!")
                .setMessage("Once you have checked out at the store or counter, you cannot log in again for the rest of the day.")
                .setCancelable(true);
        androidx.appcompat.app.AlertDialog dialog_ = builder.show();
        // Auto-dismiss after 5 seconds
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            if (dialog_.isShowing()) {
                dialog_.dismiss();
            }
        }, 8000); // 5000 milliseconds = 5 seconds
    }

}
