package com.cpm.lorealbaautomation.upload;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import androidx.annotation.NonNull;

import com.google.gson.JsonObject;
import com.cpm.lorealbaautomation.BuildConfig;
import com.cpm.lorealbaautomation.CounterLoginActivity;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.gettersetter.AuditDataGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.GroomingGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaautomation.gsonGetterSetter.MEMEAuditQuestion;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfile;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterRetailExcellence;
import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster;
import com.cpm.lorealbaautomation.retrofit.PostApi;

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

import java.io.File;
import java.util.ArrayList;
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 CommonUpload {
    Context context;
    ProgressDialog loading;
    Lorealba_Database db;
    private double lat = 0.0;
    private double lon = 0.0;
    String username, counter_id, visit_date;
    ArrayList<MasterProfile> baProfile_ImageList = new ArrayList<>();
    ArrayList<JourneyPlan> counterprofile_imgList = new ArrayList<>();
    ArrayList<MEMEAuditQuestion> meQuizList = new ArrayList<>();
    ArrayList<MasterRetailExcellence> masterRetailExcellenceArrayList = new ArrayList<>();
    ArrayList<ProductMaster> productMasterArrayList = new ArrayList<>();
    ArrayList<GroomingGetterSetter> groomingList = new ArrayList<>();
    ArrayList<JourneyPlan> counterList = new ArrayList<>();

    public CommonUpload(Context context, Lorealba_Database db, ProgressDialog loading, String counterId, String visit_date, String username, double lat, double lon) {
        this.context = context;
        this.username = username;
        this.counter_id = counterId;
        this.visit_date = visit_date;
        this.loading = loading;
        this.lat = lat;
        this.lon = lon;
        this.db = db;

    }

    public void CommonUploadwithrecursive(Context context, Lorealba_Database db, boolean previous_date) {
        db.open();
        baProfile_ImageList = db.getBaProfileListData(visit_date, counter_id, previous_date);
        counterprofile_imgList = db.getCounterProfileListData(visit_date, counter_id, previous_date);
        meQuizList = db.getme_quiz_from(visit_date, counter_id, previous_date);
        groomingList = db.getgroomingdata(counter_id, visit_date, previous_date);
        masterRetailExcellenceArrayList = db.getRetailExcellence_from(visit_date, counter_id, previous_date);
        productMasterArrayList = db.getProductMasterMeSale_from(visit_date, counter_id, previous_date);
        db.open();
        counterList = db.getba_counterimgList(counter_id, visit_date, previous_date);
        loading = ProgressDialog.show(context, "Uploading Data", "Please wait...", false, false);
        if (!baProfile_ImageList.isEmpty()) {
            UploadBaProfile(loading, db, baProfile_ImageList, 0);
        } else if (!counterprofile_imgList.isEmpty()) {
            UploadCounterProfile(loading, db, counterprofile_imgList, 0);
        } else if (!meQuizList.isEmpty()) {
            UploadMeQuiz(loading, db, meQuizList, 0);
        } else if (!groomingList.isEmpty()) {
            UploadGrooming(loading, db, groomingList, 0);
        } else if (!counterList.isEmpty()) {
            UploadCounter(loading, db, counterList, 0);
        } else if (!masterRetailExcellenceArrayList.isEmpty()) {
            UploadRetailExcellence(loading, db, masterRetailExcellenceArrayList, 0);
        } else if (!productMasterArrayList.isEmpty()) {
            UploadMeSaleData(loading, db, productMasterArrayList, 0);
        }
    }

    private void UploadMeSaleData(ProgressDialog loading, Lorealba_Database db, ArrayList<ProductMaster> productMasterArrayListData, int consumerIndex) {
        try {
            if (!productMasterArrayList.isEmpty()) {
                ArrayList<ProductMaster> productMasterArrayList = db.getMeSaledata(null, productMasterArrayListData.get(consumerIndex).getUser_id(), visit_date, counter_id);
                if (!productMasterArrayList.isEmpty()) {
                    db.open();
                    JourneyPlan jcp_Object = db.getBIDfromJCP(productMasterArrayList.get(consumerIndex).getUser_id(), counter_id);
                    JSONArray consumerUserInfoArray = getJsonArray(productMasterArrayList, jcp_Object);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("MID", jcp_Object.getMID());
                    jsonObject.put("Keys", "ME_Sale_Data");
                    jsonObject.put("JsonData", consumerUserInfoArray.toString());
                    jsonObject.put("UserId", username.toLowerCase());
                    upload_ME_Sale_Data(jsonObject.toString(), loading, db, productMasterArrayList.get(consumerIndex), consumerIndex);
                }
            }

        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    private @NonNull JSONArray getJsonArray(ArrayList<ProductMaster> productMasterArrayList, JourneyPlan jcp_Object) throws JSONException {
        JSONArray consumerUserInfoArray = new JSONArray();
        for (int k = 0; k < productMasterArrayList.size(); k++) {
            if (productMasterArrayList.get(k).getStock() > 0) {
                JSONObject obj = new JSONObject();
                obj.put("MID", jcp_Object.getMID());
                obj.put("BID", jcp_Object.getBID());
                obj.put("UserId", username.toLowerCase());
                obj.put("VisiteDate", visit_date);
                obj.put("ProductId", productMasterArrayList.get(k).getProductId());
                obj.put("Sale", productMasterArrayList.get(k).getStock());
                consumerUserInfoArray.put(obj);
            }
        }
        return consumerUserInfoArray;
    }

    public void upload_ME_Sale_Data(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final ProductMaster object, final int index) {
        try {
            final int[] finalJsonIndex = {index};
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter;
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String data = null;
                    if (response.isSuccessful()) {
                        try {
                            assert response.body() != null;
                            data = response.body().get("UploadJsonResult").toString();
                            if (!data.isEmpty()) {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.update_me_sale(counter_id, object.getUser_id());
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != productMasterArrayList.size()) {
                                        UploadMeSaleData(loading, db, productMasterArrayList, finalJsonIndex[0]);
                                    } else {
                                        Checkout_service(loading, context, lat, lon, username, counter_id, visit_date, db, false);
                                        ////finish activity...........
                                        //  loading.dismiss();
                                        //  calling_method();
                                    }
                                } else {
                                    loading.dismiss();
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Me Sale). Please LogOut Again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                    loading.dismiss();
                }
            });

        } catch (Exception e) {
            loading.dismiss();
            e.fillInStackTrace();
        }
    }


    private void UploadRetailExcellence(ProgressDialog loading, Lorealba_Database db, ArrayList<MasterRetailExcellence> me_quizList, int consumerIndex) {
        try {
            if (!me_quizList.isEmpty()) {
                ArrayList<MasterRetailExcellence> masterRetailExcellence = db.getRetailExcellencedata(null, masterRetailExcellenceArrayList.get(consumerIndex).getUser_Id(), visit_date, counter_id);
                if (!masterRetailExcellence.isEmpty()) {
                    db.open();
                    JourneyPlan jcp_Object = db.getBIDfromJCP(me_quizList.get(consumerIndex).getUser_Id(), counter_id);
                    JSONObject jsonObject = getJsonObject(masterRetailExcellence, jcp_Object);
                    // upload_Retail_Excellence_Data(jsonObject.toString(), loading, db, masterRetailExcellence.get(consumerIndex), consumerIndex);
                    upload_retail_excellence(jsonObject.toString(), loading, db, masterRetailExcellence.get(consumerIndex), consumerIndex);
                }
            }
        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    private @NonNull JSONObject getJsonObject(ArrayList<MasterRetailExcellence> masterRetailExcellence, JourneyPlan jcp_Object) throws JSONException {
        JSONArray consumerUserInfoArray = new JSONArray();
        for (int k = 0; k < masterRetailExcellence.size(); k++) {
            JSONObject obj = getJsonObject(masterRetailExcellence, jcp_Object, k);
            consumerUserInfoArray.put(obj);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("MID", jcp_Object.getMID());
        jsonObject.put("Keys", "Retail_Excellence_Data");
        jsonObject.put("JsonData", consumerUserInfoArray.toString());
        jsonObject.put("UserId", username.toLowerCase());
        return jsonObject;
    }

    private @NonNull JSONObject getJsonObject(ArrayList<MasterRetailExcellence> masterRetailExcellence, JourneyPlan jcp_Object, int k) throws JSONException {
        JSONObject obj = new JSONObject();
        obj.put("MID", jcp_Object.getMID());
        obj.put("BID", jcp_Object.getBID());
        obj.put("UserId", username.toLowerCase());
        obj.put("VisiteDate", visit_date);
        obj.put("ItemCategoryId", masterRetailExcellence.get(k).getItemCatId());
        obj.put("ItemId", masterRetailExcellence.get(k).getItemId());
        if (masterRetailExcellence.get(k).getAnswer().equalsIgnoreCase("Yes")) {
            obj.put("Available", 1);
        } else {
            obj.put("Available", 0);
        }
        return obj;
    }

    public void upload_retail_excellence(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final MasterRetailExcellence object, final int index) {
        try {
            final int[] finalJsonIndex = {index};
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter;
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String data = null;
                    if (response.isSuccessful()) {
                        try {
                            assert response.body() != null;
                            data = response.body().get("UploadJsonResult").toString();
                            if (!data.isEmpty()) {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.update_retail_excellence(counter_id, object.getUser_Id());
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != masterRetailExcellenceArrayList.size()) {
                                        UploadRetailExcellence(loading, db, masterRetailExcellenceArrayList, finalJsonIndex[0]);
                                    } else {
                                        ////finish activity...........
                                        Checkout_service(loading, context, lat, lon, username, counter_id, visit_date, db, false);
                                    }
                                } else {
                                    loading.dismiss();
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Retail Excellence). Please LogOut Again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                    loading.dismiss();
                }
            });

        } catch (Exception e) {
            loading.dismiss();
            e.fillInStackTrace();
        }
    }


    public static void Checkout_service(ProgressDialog loading, final Context context, double lat, double lon, final String username, String counter_id, String visit_date, final Lorealba_Database db, boolean flag) {
        try {
            if (flag) {
                loading = ProgressDialog.show(context, "Processing", "Please wait...", false, false);
            }

            JSONObject jsonObject = new JSONObject();
            //Ravi Changes
            jsonObject.put("UserId", username);
            jsonObject.put("CounterId", counter_id);
            jsonObject.put("Latitude", lat);
            jsonObject.put("Longitude", lon);
            jsonObject.put("VisitDate", visit_date);
            String jsonString = jsonObject.toString();
            try {
                final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                        TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
                RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString);
                Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
                PostApi api = adapter.create(PostApi.class);
                // Call<ResponseBody> call = api.getLogout(jsonData);
                //Ravi Changes
                Call<ResponseBody> call = api.getLogoutResetImei(jsonData);
                final ProgressDialog finalLoading = loading;
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                        ResponseBody responseBody = response.body();
                        String data = null;
                        if (responseBody != null && response.isSuccessful()) {
                            try {
                                assert response.body() != null;
                                data = response.body().string();
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equals("1")) {
                                    finalLoading.dismiss();
                                    db.open();
                                    db.updateLoginData(username, "", false);
                                    //Ravi Changes
                                    delete_local_database(context);
                                    Intent intent = new Intent(context, CounterLoginActivity.class);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    context.startActivity(intent);
                                    AlertandMessages.showToastMsg(context, "Logout Successfully.");
                                } else if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) {
                                    AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.KEY_FAILURE + " Please LogOut Again");
                                    finalLoading.dismiss();
                                }
                            } catch (Exception e) {
                                finalLoading.dismiss();
                                e.fillInStackTrace();
                                AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                            }
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                        finalLoading.dismiss();
                        AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                    }
                });

            } catch (Exception e) {
                loading.dismiss();
                e.fillInStackTrace();
                AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
            }

        } catch (JSONException e) {
            loading.dismiss();
            AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
        }
    }

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

            Lorealba_Database db = new Lorealba_Database(context);
            db.open();

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

        return deleted;
    }

    private void UploadBaProfile(ProgressDialog loading, Lorealba_Database db, ArrayList<MasterProfile> baProfile_ImageList, int consumerIndex) {
        try {
            JSONArray topUpArray = new JSONArray();
            JSONArray storeDetail = new JSONArray();
            ArrayList<AuditDataGetterSetter> ba_profile_auditList = db.getAfterSaveAuditQuestionAnswerData(baProfile_ImageList.get(consumerIndex).getUserId(), null);
            if (!ba_profile_auditList.isEmpty()) {
                for (int j = 0; j < ba_profile_auditList.size(); j++) {
                    JSONObject obj = new JSONObject();
                    obj.put("Category_Id", ba_profile_auditList.get(j).getCATEGORY_ID());
                    obj.put("Question_Id", ba_profile_auditList.get(j).getQUESTION_ID());
                    obj.put("Question", ba_profile_auditList.get(j).getQUESTION());
                    obj.put("Answer_type", ba_profile_auditList.get(j).getANSWER_TYPE());
                    obj.put("Answer_Id", ba_profile_auditList.get(j).getANSWER_ID());
                    obj.put("Answer", ba_profile_auditList.get(j).getANSWER());
                    obj.put("Visit_Date", baProfile_ImageList.get(consumerIndex).getViisitDate());
                    db.open();
                    obj.put("MID", db.getBIDfromJCP(baProfile_ImageList.get(consumerIndex).getUserId(), counter_id).getMID());
                    obj.put("UserId", baProfile_ImageList.get(consumerIndex).getUserId());
                    obj.put("Counter_id", counter_id);
                    topUpArray.put(obj);
                }
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Address", baProfile_ImageList.get(consumerIndex).getAddress());
            jsonObject.put("Dob", baProfile_ImageList.get(consumerIndex).getDob());
            jsonObject.put("Mobile_no", baProfile_ImageList.get(consumerIndex).getMobile());
            jsonObject.put("Email_Address", baProfile_ImageList.get(consumerIndex).getEmail());
            jsonObject.put("Instagram_Address", baProfile_ImageList.get(consumerIndex).getInstragramAddress());
            jsonObject.put("Profile_pic", baProfile_ImageList.get(consumerIndex).getProfilePic());
            jsonObject.put("Location", baProfile_ImageList.get(consumerIndex).getLocation());
            jsonObject.put("Landmark", baProfile_ImageList.get(consumerIndex).getLandmark());
            db.open();
            jsonObject.put("MID", db.getBIDfromJCP(baProfile_ImageList.get(consumerIndex).getUserId(), counter_id).getMID());
            jsonObject.put("UserId", baProfile_ImageList.get(consumerIndex).getUserId());
            jsonObject.put("Counter_id", counter_id);
            if (!ba_profile_auditList.isEmpty()) {
                jsonObject.put("BA_PROFILE_DATA", topUpArray);
            } else {
                jsonObject.put("BA_PROFILE_DATA", "");
            }
            storeDetail.put(jsonObject);

            JSONObject jsonFinalObject = new JSONObject();
            db.open();
            jsonFinalObject.put("MID", db.getBIDfromJCP(baProfile_ImageList.get(consumerIndex).getUserId(), counter_id).getMID());
            jsonFinalObject.put("Keys", "BaProfileData");
            jsonFinalObject.put("JsonData", storeDetail.toString());
            jsonFinalObject.put("UserId", baProfile_ImageList.get(consumerIndex).getUserId());
            upload_BaProfilewithaudit(jsonFinalObject.toString(), loading, baProfile_ImageList.get(consumerIndex), consumerIndex);
        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    public void upload_BaProfilewithaudit(String jsondata, final ProgressDialog loading, final MasterProfile object, final int index) {
        try {
            final int[] finalJsonIndex = {index};
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter;
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String data = null;
                    if (response.isSuccessful()) {
                        try {
                            assert response.body() != null;
                            data = response.body().get("UploadJsonResult").toString();
                            if (!data.isEmpty()) {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.updateBaProfileStatus(object.getUserId(), object.getViisitDate(), CommonString.KEY_Y);
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != baProfile_ImageList.size()) {
                                        UploadBaProfile(loading, db, baProfile_ImageList, finalJsonIndex[0]);
                                    } else if (!counterprofile_imgList.isEmpty()) {
                                        UploadCounterProfile(loading, db, counterprofile_imgList, 0);
                                    } else if (!meQuizList.isEmpty()) {
                                        UploadMeQuiz(loading, db, meQuizList, 0);
                                    } else if (!groomingList.isEmpty()) {
                                        UploadGrooming(loading, db, groomingList, 0);
                                    } else if (!counterList.isEmpty()) {
                                        UploadCounter(loading, db, counterList, 0);
                                    } else {
                                        Checkout_service(loading, context, lat, lon, username, counter_id, visit_date, db, false);
                                    }
                                } else {
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Ba Profile). Please LogOut Again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    loading.dismiss();
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                }
            });

        } catch (Exception e) {
            loading.dismiss();
            e.fillInStackTrace();
        }
    }

    private void UploadCounterProfile(ProgressDialog loading, Lorealba_Database db, ArrayList<JourneyPlan> counterimgList, int consumerIndex) {
        try {
            JSONArray storeDetail = new JSONArray();
            JSONObject jsonObject;
            if (!counterimgList.isEmpty()) {
                jsonObject = new JSONObject();
                db.open();
                jsonObject.put("MID", db.getBIDfromJCP(counterimgList.get(consumerIndex).getUserId(), counter_id).getMID());
                jsonObject.put("UserId", counterimgList.get(consumerIndex).getUserId());
                jsonObject.put("ProfileImage1", counterimgList.get(consumerIndex).getProfileImage1());
                jsonObject.put("ProfileImage2", counterimgList.get(consumerIndex).getProfileImage2());
                jsonObject.put("Counterlength", counterimgList.get(consumerIndex).getCounterlength());
                jsonObject.put("Counterwidth", counterimgList.get(consumerIndex).getCounterwidth());
                jsonObject.put("SetupDate", counterimgList.get(consumerIndex).getSetupDate());
                jsonObject.put("Visit_Date", visit_date);
                jsonObject.put("Counter_id", counter_id);
                storeDetail.put(jsonObject);
            }

            jsonObject = new JSONObject();
            db.open();
            jsonObject.put("MID", db.getBIDfromJCP(counterimgList.get(consumerIndex).getUserId(), counter_id).getMID());
            jsonObject.put("Keys", "ConterProfileData");
            jsonObject.put("JsonData", storeDetail.toString());
            jsonObject.put("UserId", counterimgList.get(consumerIndex).getUserId());
            upload_CounterProfile(jsonObject.toString(), loading, db, counterimgList.get(consumerIndex), consumerIndex);

        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    public void upload_CounterProfile(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final JourneyPlan object, final int index) {
        try {
            final int[] finalJsonIndex = {index};
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter;
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String data = null;
                    if (response.isSuccessful()) {
                        try {
                            assert response.body() != null;
                            data = response.body().get("UploadJsonResult").toString();
                            if (!data.isEmpty()) {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.updateCounterProfileStatus(object.getUserId(), visit_date, CommonString.KEY_Y);
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != counterprofile_imgList.size()) {
                                        UploadCounterProfile(loading, db, counterprofile_imgList, finalJsonIndex[0]);
                                    } else if (!meQuizList.isEmpty()) {
                                        UploadMeQuiz(loading, db, meQuizList, 0);
                                    } else if (!groomingList.isEmpty()) {
                                        UploadGrooming(loading, db, groomingList, 0);
                                    } else if (!counterList.isEmpty()) {
                                        UploadCounter(loading, db, counterList, 0);
                                    } else {
                                        Checkout_service(loading, context, lat, lon, username, counter_id, visit_date, db, false);
                                    }
                                } else {
                                    loading.dismiss();
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Counter Profile). Please LogOut Again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                    loading.dismiss();
                }
            });

        } catch (Exception e) {
            e.fillInStackTrace();
            loading.dismiss();
        }
    }

    private void UploadMeQuiz(ProgressDialog loading, Lorealba_Database db, ArrayList<MEMEAuditQuestion> me_quizList, int consumerIndex) {
        try {
            if (!me_quizList.isEmpty()) {
                ArrayList<MEMEAuditQuestion> specific_meQuizList = db.getme_quiz_from_database(null, me_quizList.get(consumerIndex).getUser_Id(), visit_date, counter_id, null);
                if (!specific_meQuizList.isEmpty()) {
                    JourneyPlan jcp_Object = db.getBIDfromJCP(me_quizList.get(consumerIndex).getUser_Id(), counter_id);
                    JSONArray consumerUserInfoArray = new JSONArray();
                    for (int k = 0; k < me_quizList.size(); k++) {
                        JSONObject obj = new JSONObject();

                        obj.put("MID", jcp_Object.getMID());
                        obj.put("BID", jcp_Object.getBID());
                        obj.put("VisiteDate", visit_date);
                        obj.put("UserId", specific_meQuizList.get(k).getUser_Id());
                        obj.put("QuizId", specific_meQuizList.get(k).getQuizId());
                        obj.put("Question_Id", specific_meQuizList.get(k).getQuestionId());
                        obj.put("Question_Type", specific_meQuizList.get(k).getQuestionType());
                        JSONArray compArraymult = new JSONArray();
                        JSONObject objmultians = new JSONObject();
                        if (specific_meQuizList.get(k).getQuestionType().equalsIgnoreCase("List Single Choice")) {
                            objmultians.put("Answer", specific_meQuizList.get(k).getAnswer());
                            objmultians.put("Answer_Id", specific_meQuizList.get(k).getAnswerId());
                            objmultians.put("Answer_Image", specific_meQuizList.get(k).getStr_audit_img());
                            compArraymult.put(objmultians);
                        } else if (!specific_meQuizList.get(k).getQuestionType().equalsIgnoreCase("List Multiple Choice")) {
                            objmultians.put("Answer", specific_meQuizList.get(k).getAnswer());
                            objmultians.put("Answer_Id", 0);
                            objmultians.put("Answer_Image", "");
                            compArraymult.put(objmultians);
                        } else {
                            db.open();
                            ArrayList<MEMEAuditQuestion> multiansList = db.getquiz_answer(specific_meQuizList.get(k).getKeyId());
                            if (!multiansList.isEmpty()) {
                                for (int j2 = 0; j2 < multiansList.size(); j2++) {
                                    objmultians = new JSONObject();
                                    objmultians.put("Answer", multiansList.get(j2).getAnswer());
                                    objmultians.put("Answer_Id", multiansList.get(j2).getAnswerId());
                                    objmultians.put("Answer_Image", "");
                                    compArraymult.put(objmultians);
                                }
                            }
                        }
                        obj.put("AnsList", compArraymult);
                        consumerUserInfoArray.put(obj);
                    }

                    JSONObject jsonObject = new JSONObject();
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_id);
                    jsonObject.put("MID", jcp_Object.getMID());
                    jsonObject.put("Keys", "ME_Quiz_Data");
                    jsonObject.put("JsonData", consumerUserInfoArray.toString());
                    jsonObject.put("UserId", me_quizList.get(consumerIndex).getUser_Id().toLowerCase());
                    upload_me_Quiz(jsonObject.toString(), loading, db, me_quizList.get(consumerIndex), consumerIndex);
                }
            }
        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    public void upload_me_Quiz(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final MEMEAuditQuestion object, final int index) {
        try {
            final int[] finalJsonIndex = {index};

            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter;
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String data = null;
                    if (response.isSuccessful()) {
                        try {
                            assert response.body() != null;
                            data = response.body().get("UploadJsonResult").toString();
                            if (!data.isEmpty()) {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.update_Me_Quiz(counter_id, object.getUser_Id());
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != meQuizList.size()) {
                                        UploadMeQuiz(loading, db, meQuizList, finalJsonIndex[0]);
                                    } else if (!groomingList.isEmpty()) {
                                        UploadGrooming(loading, db, groomingList, 0);
                                    } else if (!counterList.isEmpty()) {
                                        UploadCounter(loading, db, counterList, 0);
                                    } else {
                                        Checkout_service(loading, context, lat, lon, username, counter_id, visit_date, db, false);
                                    }
                                } else {
                                    loading.dismiss();
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Me Quiz). Please LogOut Again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                    loading.dismiss();
                }
            });

        } catch (Exception e) {
            loading.dismiss();
            e.fillInStackTrace();
        }
    }


    private void UploadGrooming(ProgressDialog loading, Lorealba_Database db, ArrayList<GroomingGetterSetter> groomingList, int grooming_index) {
        try {
            if (!groomingList.isEmpty()) {
                db.open();
                JourneyPlan jcp_Object = db.getBIDfromJCP(groomingList.get(grooming_index).getUser_Id(), counter_id);
                JSONArray consumerUserInfoArray = getJsonArray(groomingList, grooming_index, jcp_Object);

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("MID", jcp_Object.getMID());
                jsonObject.put("Keys", "Groomed_Data");
                jsonObject.put("JsonData", consumerUserInfoArray.toString());
                jsonObject.put("UserId", groomingList.get(grooming_index).getUser_Id());
                upload_grooming(jsonObject.toString(), loading, db, groomingList.get(grooming_index), grooming_index);
            }


        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    private @NonNull JSONArray getJsonArray(ArrayList<GroomingGetterSetter> groomingList, int grooming_index, JourneyPlan jcp_Object) throws JSONException {
        JSONArray consumerUserInfoArray = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("MID", jcp_Object.getMID());
        obj.put("BID", jcp_Object.getBID());
        obj.put("VisiteDate", visit_date);
        obj.put("UserId", groomingList.get(grooming_index).getUser_Id());
        obj.put("Groomed_Morng_Img", groomingList.get(grooming_index).getMorning_groom_img_str());
        obj.put("Groomed_Morng_Time_Str", groomingList.get(grooming_index).getMorning_groom_time_str());
        obj.put("Groomed_Noon_Img", groomingList.get(grooming_index).getNoon_groom_img_str());
        obj.put("Groomed_Noon_Time_Str", groomingList.get(grooming_index).getNoon_groom_time_str());
        obj.put("Groomed_Eveng_Img", groomingList.get(grooming_index).getEvenning_groom_img_str());
        obj.put("Groomed_Eveng_Time_Str", groomingList.get(grooming_index).getEvenning_groom_time_str());

        consumerUserInfoArray.put(obj);
        return consumerUserInfoArray;
    }

    public void upload_grooming(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final GroomingGetterSetter object, final int index) {
        try {
            final int[] finalJsonIndex = {index};

            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter;
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String data = null;
                    if (response.isSuccessful()) {
                        try {
                            assert response.body() != null;
                            data = response.body().get("UploadJsonResult").toString();
                            if (!data.isEmpty()) {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.update_groomed_img(counter_id, visit_date, object.getUser_Id());
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != groomingList.size()) {
                                        UploadGrooming(loading, db, groomingList, finalJsonIndex[0]);
                                    } else if (!counterList.isEmpty()) {
                                        UploadCounter(loading, db, counterList, 0);
                                    } else {
                                        Checkout_service(loading, context, lat, lon, username, counter_id, visit_date, db, false);
                                    }

                                } else {
                                    loading.dismiss();
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Grooming). Please LogOut Again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                    loading.dismiss();
                }
            });

        } catch (Exception e) {
            e.fillInStackTrace();
            loading.dismiss();
        }
    }

    private void UploadCounter(ProgressDialog loading, Lorealba_Database db, ArrayList<JourneyPlan> counterList, int counter_index) {
        try {
            if (!counterList.isEmpty()) {
                db.open();
                JourneyPlan jcp_Object = db.getBIDfromJCP(null, counter_id);
                JSONArray consumerUserInfoArray = new JSONArray();
                JSONObject obj = new JSONObject();
                String key = "";
                if (counterList.get(counter_index).getUser_type().equalsIgnoreCase(CommonString.TAG_FROM_BA) || counterList.get(counter_index).getUser_type().equalsIgnoreCase(CommonString.TAG_FROM_TBA)) {
                    key = "Counter_Image_Data";
                    obj = new JSONObject();
                    consumerUserInfoArray = new JSONArray();
                    obj.put("MID", jcp_Object.getMID());
                    obj.put("VisitDate", visit_date);
                    obj.put("UserId", counterList.get(counter_index).getUserId());
                    obj.put("Counter_Img_One", counterList.get(counter_index).getCounter_img_onefor_ba());
                    obj.put("Counter_Img_Two", counterList.get(counter_index).getCounter_img_two_for_ba());
                    consumerUserInfoArray.put(obj);
                } else {
                    key = "ME_Counter_Image_Data";
                    obj = new JSONObject();
                    consumerUserInfoArray = new JSONArray();

                    obj.put("MID", jcp_Object.getMID());
                    obj.put("VisitDate", visit_date);
                    obj.put("UserId", counterList.get(counter_index).getUserId());
                    obj.put("PreSetUpImgOne", counterList.get(counter_index).getPresetup_img_one_str());
                    obj.put("PreSetUpImgTwo", counterList.get(counter_index).getPresetup_img_two_str());
                    obj.put("PostSetUpImgOne", counterList.get(counter_index).getPostsetup_img_one_str());
                    obj.put("PostSetUpImgTwo", counterList.get(counter_index).getPostsetup_img_two_str());
                    consumerUserInfoArray.put(obj);
                }


                JSONObject jsonObject = new JSONObject();
                jsonObject.put("MID", jcp_Object.getMID());
                jsonObject.put("Keys", key);
                jsonObject.put("JsonData", consumerUserInfoArray.toString());
                jsonObject.put("UserId", counterList.get(counter_index).getUserId());
                upload_counter(jsonObject.toString(), loading, db, counterList.get(counter_index), counter_index);
            }


        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    public void upload_counter(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final JourneyPlan object, final int index) {
        try {
            final int[] finalJsonIndex = {index};
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String data = null;
                    if (response.isSuccessful()) {
                        try {
                            assert response.body() != null;
                            data = response.body().get("UploadJsonResult").toString();
                            if (!data.isEmpty()) {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.update_ba_counter_img(counter_id, visit_date, object.getUserId(), object.getTransId());
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != groomingList.size()) {
                                        UploadCounter(loading, db, counterList, finalJsonIndex[0]);
                                    } else {
                                        Checkout_service(loading, context, lat, lon, username, counter_id, visit_date, db, false);
                                    }
                                } else {
                                    loading.dismiss();
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Counter). Please LogOut Again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                    loading.dismiss();
                }
            });

        } catch (Exception e) {
            e.fillInStackTrace();
            loading.dismiss();
        }
    }
}
