package com.cpm.lorealbaautomation.download;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;

import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gettersetter.BaProfileGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.GroomingGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaautomation.gsonGetterSetter.MEMEAuditQuestion;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBreak;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPosm;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfile;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterRetailExcellence;
import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster;
import com.cpm.lorealbaautomation.gsonGetterSetter.TStockSummaryGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.T_LeaveRequest;
import com.cpm.lorealbaautomation.retrofit.PostApi;
import com.cpm.lorealbaautomation.retrofit.PostApiForUpload;
import com.cpm.lorealbaautomation.retrofit.StringConverterFactory;
import com.squareup.okhttp.MultipartBuilder;

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

import java.io.File;
import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

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

public class Downloader extends JobIntentService {
    private static final int UNIQUE_JOB_ID = 1337;
    Context context;
    Lorealba_Database db;
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    String uploadimg_str;
    protected TStockSummaryGetterSetter tStockSummaryObj;
    private String counter_id;
    private String visit_date;
    private String username;
    int mid = 0;
    BaProfileGetterSetter baProfile;
    JourneyPlan counterimg_object;
    MasterProfile baProfileImage;
    ArrayList<MasterPosm> visibilityEliment = new ArrayList<>();
    T_LeaveRequest leaveRequestObject;
    MasterBreak breakManagementObject;
    InvoiceGetterSetter me_makeover_captueObject;
    ArrayList<InvoiceGetterSetter> me_makeoverList = new ArrayList<>();
    ArrayList<MEMEAuditQuestion> quizList = new ArrayList<>();
    ArrayList<ProductMaster> productMasterArrayList = new ArrayList<>();
    ArrayList<MasterRetailExcellence> masterRetailExcellenceArrayList = new ArrayList<>();
    JourneyPlan ba_counter_imges_dataObject, me_counter_imges_dataObject;
    GroomingGetterSetter groomedImagGetterSetter;

    public static void enqueueWork(Context ctxt, Intent i) {
        enqueueWork(ctxt, Downloader.class, UNIQUE_JOB_ID, i);
    }

    @Override
    public void onHandleWork(Intent intent) {
        context = getApplicationContext();
        preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        db = new Lorealba_Database(context);
        db.open();
        counterimg_object = (JourneyPlan) intent.getSerializableExtra(CommonString.KEY_CounterProfile);
        baProfile = (BaProfileGetterSetter) intent.getSerializableExtra(CommonString.KEY_BaProfile_list);
        baProfileImage = (MasterProfile) intent.getSerializableExtra(CommonString.KEY_BaProfile);
        visibilityEliment = (ArrayList<MasterPosm>) intent.getSerializableExtra(CommonString.KEY_VisibilityEliment);
        leaveRequestObject = (T_LeaveRequest) intent.getSerializableExtra(CommonString.KEY_LEAVE_Mangemennt);
        breakManagementObject = (MasterBreak) intent.getSerializableExtra(CommonString.KEY_Break_Mangemennt);
        ba_counter_imges_dataObject = (JourneyPlan) intent.getSerializableExtra(CommonString.KEY_BA_Counter_Image);
        me_counter_imges_dataObject = (JourneyPlan) intent.getSerializableExtra(CommonString.KEY_Me_Counter_Image);
        ///change jp
        groomedImagGetterSetter = (GroomingGetterSetter) intent.getSerializableExtra(CommonString.KEY_Groomed_Image);
        uploadimg_str = intent.getStringExtra(CommonString.KEY_UPLOADIMAGE);
        ArrayList<JourneyPlan> jcp = db.getStoreData(visit_date, null, counter_id);
        quizList = (ArrayList<MEMEAuditQuestion>) intent.getSerializableExtra(CommonString.KEY_ME_QUIZ);
        masterRetailExcellenceArrayList = (ArrayList<MasterRetailExcellence>) intent.getSerializableExtra(CommonString.KEY_RETAIL_EXCELLENCE);
        productMasterArrayList = (ArrayList<ProductMaster>) intent.getSerializableExtra(CommonString.ME_SALE);

        me_makeover_captueObject = (InvoiceGetterSetter) intent.getSerializableExtra(CommonString.KEY_Me_MakeOver_Capture);
        if (jcp.size() > 0) {
            mid = jcp.get(0).getMID();
        }

        //Corrected 01-12-20
        if (quizList != null) {
            ////for upload quiz data me
            quizList = db.getme_quiz_from_database(null, null, visit_date, counter_id, null);
            calculate_me_quiz_data(db.getBIDfromJCP(username, counter_id), quizList);
        } else if (masterRetailExcellenceArrayList != null) {
            masterRetailExcellenceArrayList = db.getRetailExcellencedata(null, null, visit_date, counter_id);
            calculate_retail_excellence_data(db.getBIDfromJCP(username, counter_id), masterRetailExcellenceArrayList);
        } else if (productMasterArrayList != null) {
            productMasterArrayList = db.getMeSaledata(null, null, visit_date, counter_id);
            calculate_me_sale_data(db.getBIDfromJCP(username, counter_id), productMasterArrayList);
        } else if (counterimg_object != null) {
            UploadCounterProfile();
        } else if (baProfileImage != null) {
            UploadBaProfile();
        } else if (visibilityEliment != null) {
            UploadVisibilityElement();
        } else if (leaveRequestObject != null) {
            String TransId = leaveRequestObject.getTransId();
            db.open();
            leaveRequestObject = db.getinserted_leave_request_data(counter_id, username, visit_date, TransId, false);
            if (leaveRequestObject.getTransId() != null && !leaveRequestObject.getTransId().equals("")) {
                calculate_leave_data(leaveRequestObject);
            }
        } else if (me_makeover_captueObject != null) {
            db.open();
            me_makeoverList = db.getMakeoverCapture(visit_date, counter_id);
            calculate_me_makeoverdata(me_makeoverList, 0);

        } else if (breakManagementObject != null) {
            String TransId = breakManagementObject.getTransId();
            db.open();
            breakManagementObject = db.getBreakManagementforuploadList(counter_id, visit_date, username, TransId, false);
            if (breakManagementObject.getBreakId() != null && !breakManagementObject.getEndTym().equals("")) {
                calculate_break_data(breakManagementObject);
            }
        } else if (ba_counter_imges_dataObject != null) {
            String TransId = ba_counter_imges_dataObject.getTransId();
            db.open();
            ba_counter_imges_dataObject = db.getba_counter_img(counter_id, visit_date, username, TransId);
            calculate_ba_counter_imgage_data(ba_counter_imges_dataObject);
        } else if (me_counter_imges_dataObject != null) {
            String TransId = me_counter_imges_dataObject.getTransId();
            db.open();
            me_counter_imges_dataObject = db.getba_counter_img(counter_id, visit_date, username, TransId);
            calculate_me_counter_imgage_data(me_counter_imges_dataObject);
        } else if (groomedImagGetterSetter != null) {
            db.open();
            groomedImagGetterSetter = db.getinserted_groomingdata(counter_id, username, visit_date);
            calculate_Groomed_Image_Data(groomedImagGetterSetter);
        }
        if (uploadimg_str != null && !getFileNames(new File(CommonString.getImagesFolder(context)).listFiles()).isEmpty()) {
            UploadImageRecursive();
        }
    }

    private void UploadVisibilityElement() {
        try {
            JSONArray topUpArray = new JSONArray();
            if (visibilityEliment != null) {
                for (int j = 0; j < visibilityEliment.size(); j++) {
                    JSONObject obj = new JSONObject();
                    obj.put("MID", mid);
                    obj.put("UserId", username);
                    obj.put("PosmId", visibilityEliment.get(j).getPosmId());
                    obj.put("PosmTypeId", visibilityEliment.get(j).getPosmTypeId());
                    obj.put("Counter_id", counter_id);

                    if (visibilityEliment.get(j).getPromotion_exists_state().equalsIgnoreCase("Yes")) {
                        obj.put("Promotion_Exists", "1");
                        obj.put("Promo_Img", visibilityEliment.get(j).getPromotion_img());
                        obj.put("PReason_Id", "0");
                    } else {
                        obj.put("Promotion_Exists", "0");
                        obj.put("Promo_Img", "");
                        obj.put("PReason_Id", visibilityEliment.get(j).getPromotion_currect_ans_Id());
                    }
                    topUpArray.put(obj);
                }
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("MID", mid);
            jsonObject.put("Keys", "VisibiliElementData");
            jsonObject.put("JsonData", topUpArray.toString());
            jsonObject.put("UserId", username);

            String jsonString = jsonObject.toString();

            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<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    if (visibilityEliment.size() > 0) {
                                        db.updateVisibilityStatus(visibilityEliment.get(0).getTransId());
                                        db.open();
                                        db.updateMasterTransactionDataStatus(visibilityEliment.get(0).getTransId());
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    }
                }

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

                }
            });


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

    private void UploadBaProfile() {
        try {
            JSONArray topUpArray = new JSONArray();
            JSONArray storeDetail = new JSONArray();
            if (baProfileImage != null) {
                if (baProfile != null && !baProfile.getBaProfileList().isEmpty()) {
                    for (int j = 0; j < baProfile.getBaProfileList().size(); j++) {
                        JSONObject obj = getJsonObject(j);
                        topUpArray.put(obj);
                    }
                }

                if (baProfileImage != null && baProfileImage.getProfilePic() != null && !baProfileImage.getProfilePic().isEmpty()) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("Address", baProfileImage.getAddress());
                    jsonObject.put("Dob", baProfileImage.getDob());
                    jsonObject.put("Mobile_no", baProfileImage.getMobile());
                    jsonObject.put("Email_Address", baProfileImage.getEmail());
                    jsonObject.put("Instagram_Address", baProfileImage.getInstragramAddress());
                    jsonObject.put("Profile_pic", baProfileImage.getProfilePic());
                    jsonObject.put("Location", baProfileImage.getLocation());
                    jsonObject.put("Landmark", baProfileImage.getLandmark());
                    jsonObject.put("MID", mid);
                    jsonObject.put("UserId", username);
                    jsonObject.put("Counter_id", counter_id);
                    if (baProfile != null && !baProfile.getBaProfileList().isEmpty()) {
                        jsonObject.put("BA_PROFILE_DATA", topUpArray);
                    } else {
                        jsonObject.put("BA_PROFILE_DATA", "");
                    }
                    storeDetail.put(jsonObject);
                }
                Log.d("uploadProfiledata",storeDetail.toString());
                JSONObject jsonFinalObject = new JSONObject();
                jsonFinalObject.put("MID", mid);
                jsonFinalObject.put("Keys", "BaProfileData");
                jsonFinalObject.put("JsonData", storeDetail.toString());
                jsonFinalObject.put("UserId", username);
                upload_BaProfilewithaudit(jsonFinalObject.toString());
            }
        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    @NonNull
    private JSONObject getJsonObject(int j) throws JSONException {
        JSONObject obj = new JSONObject();
        obj.put("Category_Id", baProfile.getBaProfileList().get(j).getCATEGORY_ID());
        obj.put("Question_Id", baProfile.getBaProfileList().get(j).getQUESTION_ID());
        obj.put("Question", baProfile.getBaProfileList().get(j).getQUESTION());
        obj.put("Answer_type", baProfile.getBaProfileList().get(j).getANSWER_TYPE());
        obj.put("Answer_Id", baProfile.getBaProfileList().get(j).getANSWER_ID());
        obj.put("Answer", baProfile.getBaProfileList().get(j).getANSWER());
        obj.put("OthersTextValue", baProfile.getBaProfileList().get(j).getSpin_others_for_edt());
        obj.put("Visit_Date", visit_date);
        obj.put("MID", mid);
        obj.put("UserId", username);
        obj.put("Counter_id", counter_id);
        return obj;
    }

    private void UploadCounterProfile() {
        try {
            JSONArray storeDetail = new JSONArray();
            JSONObject jsonObject;
            db.open();
            counterimg_object = db.getCounterProfileData(username, visit_date, counter_id, false);
            if (counterimg_object.getUserId() != null && !counterimg_object.getUserId().equals("")) {
                jsonObject = new JSONObject();
                jsonObject.put("MID", mid);
                jsonObject.put("UserId", username);
                jsonObject.put("ProfileImage1", counterimg_object.getProfileImage1());
                jsonObject.put("ProfileImage2", counterimg_object.getProfileImage2());
                jsonObject.put("Counterlength", counterimg_object.getCounterlength());
                jsonObject.put("Counterwidth", counterimg_object.getCounterwidth());
                jsonObject.put("SetupDate", counterimg_object.getSetupDate());
                jsonObject.put("Visit_Date", visit_date);
                jsonObject.put("Counter_id", counter_id);
                storeDetail.put(jsonObject);

                jsonObject = new JSONObject();
                jsonObject.put("MID", mid);
                jsonObject.put("Keys", "ConterProfileData");
                jsonObject.put("JsonData", storeDetail.toString());
                jsonObject.put("UserId", username);
                upload_CounterProfile(jsonObject.toString(), counterimg_object);
            }
        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    private void calculate_leave_data(T_LeaveRequest leaveRequestObject) {
        try {
            JourneyPlan jcpfor_bid = db.getBIDfromJCP(username, counter_id);
            JSONArray promoArray = new JSONArray();
            JSONObject obj = new JSONObject();
            obj.put("MID", jcpfor_bid.getMID());
            obj.put("BID", jcpfor_bid.getBID());
            obj.put("UserId", username);

            obj.put("TranId", leaveRequestObject.getTransId());
            obj.put("Applied_Date", leaveRequestObject.getUpload_request_date());
            obj.put("From_Date", leaveRequestObject.getUpload_start_date_str());
            obj.put("End_Date", leaveRequestObject.getUpload_end_date_str());
            obj.put("Leave_Type", leaveRequestObject.getOne_day_leave_str());
            obj.put("Leave_TypeId", leaveRequestObject.getStr_leaveTypeId());
            obj.put("Reason", leaveRequestObject.getLeave_reason());
            promoArray.put(obj);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("MID", jcpfor_bid.getMID());
            jsonObject.put("Keys", "RequestFor_Leave_Approval");
            jsonObject.put("JsonData", promoArray.toString());
            jsonObject.put("UserId", username);
            upload_Request_ApprovalLeave(jsonObject.toString(), leaveRequestObject);
        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    public void upload_Request_ApprovalLeave(String jsondata, final T_LeaveRequest leaveRequestObject) {
        try {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), 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 responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.updateMasterTransactionDataStatus(leaveRequestObject.getTransId());
                                    db.open();
                                    db.update_leave_management_status(counter_id, visit_date, username, leaveRequestObject.getTransId(), false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    }
                }

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

                }
            });

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

    public static String convertTym(String str) {
        SimpleDateFormat displayFormat = null;
        SimpleDateFormat parseFormat = null;
        Date date = null;
        try {
            displayFormat = new SimpleDateFormat("HH:mm");
            parseFormat = new SimpleDateFormat("hh:mm a");
            date = parseFormat.parse(str);
        } catch (ParseException e) {
            e.fillInStackTrace();
        }
        return displayFormat.format(date) + ":00";
    }

    private void calculate_break_data(MasterBreak breakManagementObject) {
        try {
            db.open();
            JourneyPlan jcpfor_bid = db.getBIDfromJCP(username, counter_id);
            JSONArray promoArray = new JSONArray();
            JSONObject obj = new JSONObject();
            obj.put("MID", jcpfor_bid.getMID());
            obj.put("BID", jcpfor_bid.getBID());
            obj.put("UserId", username);
            obj.put("VisitDate", visit_date);

            obj.put("TranId", breakManagementObject.getTransId());
            obj.put("BreakId", breakManagementObject.getBreakId().toString());
            obj.put("StartTym", convertTym(breakManagementObject.getStartTym()));
            obj.put("EndTym", convertTym(breakManagementObject.getEndTym()));
            obj.put("TotalDuration", breakManagementObject.getTotalDuration().toString());

            promoArray.put(obj);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("MID", jcpfor_bid.getMID());
            jsonObject.put("Keys", "Break_Management_Data");
            jsonObject.put("JsonData", promoArray.toString());
            jsonObject.put("UserId", username);
            upload_break_M(jsonObject.toString(), breakManagementObject);
        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    public void upload_break_M(String jsondata, final MasterBreak breakManagementObject) {
        try {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), 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 responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.updateMasterTransactionDataStatus(breakManagementObject.getTransId());
                                    db.open();
                                    db.update_break_management_status(counter_id, visit_date, username, breakManagementObject.getTransId(), false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    }
                }

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

                }
            });

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

    private void calculate_ba_counter_imgage_data(JourneyPlan ba_counter_imgObject) {
        try {
            JourneyPlan jcpfor_bid = db.getBIDfromJCP(username, counter_id);
            JSONArray promoArray = new JSONArray();
            JSONObject obj = new JSONObject();
            obj.put("MID", jcpfor_bid.getMID());
            obj.put("UserId", username);
            obj.put("VisitDate", visit_date);
            obj.put("Counter_Img_One", ba_counter_imgObject.getCounter_img_onefor_ba());
            obj.put("Counter_Img_Two", ba_counter_imgObject.getCounter_img_two_for_ba());
            promoArray.put(obj);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("MID", jcpfor_bid.getMID());
            jsonObject.put("Keys", "Counter_Image_Data");
            jsonObject.put("JsonData", promoArray.toString());
            jsonObject.put("UserId", username);
            upload_ba_counter_img(jsonObject.toString(), ba_counter_imgObject);
        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    public void upload_ba_counter_img(String jsondata, final JourneyPlan breakManagementObject) {
        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"), 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 responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                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, username, breakManagementObject.getTransId());
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    }
                }

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

                }
            });

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

    private void calculate_Groomed_Image_Data(GroomingGetterSetter groomedObject) {
        try {
            JourneyPlan jcpfor_bid = db.getBIDfromJCP(username, counter_id);
            JSONArray promoArray = new JSONArray();
            JSONObject obj = new JSONObject();
            obj.put("MID", jcpfor_bid.getMID());
            obj.put("BID", jcpfor_bid.getBID());
            obj.put("UserId", username);
            obj.put("VisitDate", visit_date);
            obj.put("Groomed_Morng_Img", groomedObject.getMorning_groom_img_str());
            obj.put("Groomed_Morng_Time_Str", groomedObject.getMorning_groom_time_str());
            obj.put("Groomed_Noon_Img", groomedObject.getNoon_groom_img_str());
            obj.put("Groomed_Noon_Time_Str", groomedObject.getNoon_groom_time_str());
            obj.put("Groomed_Eveng_Img", groomedObject.getEvenning_groom_img_str());
            obj.put("Groomed_Eveng_Time_Str", groomedObject.getEvenning_groom_time_str());

            promoArray.put(obj);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("MID", jcpfor_bid.getMID());
            jsonObject.put("Keys", "Groomed_Data");
            jsonObject.put("JsonData", promoArray.toString());
            jsonObject.put("UserId", username);
            upload_Groomrd_img_data(jsonObject.toString(), groomedObject);
        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    public void upload_Groomrd_img_data(String jsondata, final GroomingGetterSetter groomedObject) {
        try {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), 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 responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    if (!groomedObject.getMorning_groom_img_str().equals("") && !groomedObject.getNoon_groom_img_str().equals("") && !groomedObject.getNoon_groom_img_str().equals("")) {
                                        db.update_groomed_img(counter_id, visit_date, username);
                                    }


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

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

                }
            });

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

    public static ArrayList<String> getFileNames(File[] file) {
        ArrayList<String> arrayFiles = new ArrayList<String>();
        if (file != null && file.length > 0) {
            for (int i = 0; i < file.length; i++)
                arrayFiles.add(file[i].getName());
        }
        return arrayFiles;
    }

    public void UploadImageRecursive() {
        try {
            final int[] uploadedFiles = {0};
            final int[] statusforimage = {0};
            statusforimage[0] = 0;
            String filename = null, foldername = null;
            File f = new File(CommonString.getImagesFolder(context));
            ArrayList<String> finalList = new ArrayList<>();
            if (!getFileNames(f.listFiles()).isEmpty()) {
                for (int k = 0; k < getFileNames(f.listFiles()).size(); k++) {
                    if (!db.ischeck_uploaded_image(visit_date, getFileNames(f.listFiles()).get(k))) {
                        finalList.add(getFileNames(f.listFiles()).get(k));
                    }
                }
            }
            Log.e("finalList", "Downloader"+finalList.toString());
            if (!finalList.isEmpty()) {
                filename = "";
                for (int i = 0; i < finalList.size(); i++) {
                    if (new File(CommonString.getImagesFolder(context) + finalList.get(i)).exists()) {
                        if (finalList.get(i).contains("_Counter_Selfie_img_")) {
                            foldername = "BACoverageImages";
                        } else if (finalList.get(i).contains("_cp_img_one_") || finalList.get(i).contains("_cp_img_two_")) {
                            foldername = "CounterProfileImages";
                        } else if (finalList.get(i).contains("_counter_img_one_") || finalList.get(i).contains("_counter_img_two_")) {
                            foldername = "CounterImages";
                        } else if (finalList.get(i).contains("_ba_AuditPic_") || finalList.get(i).contains("_ba_profile_img_")) {
                            foldername = "BAProfileImages";
                        } else if (finalList.get(i).contains("_Damaged_stock_img_") || finalList.get(i).contains("_Damage_header_img_")) {
                            foldername = "DamageStockImages";
                        } else if (finalList.get(i).contains("_groomed_img_mrng_") || finalList.get(i).contains("_groomed_img_noon_") || finalList.get(i).contains("_groomed_img_evning_")) {
                            foldername = "GroomingImages";
                        } else if (finalList.get(i).contains("_stock_check_img_") || finalList.get(i).contains("_tester_stock_img_") || finalList.get(i).contains("_suggested_stk_img") || finalList.get(i).contains("_Sample_stock_img")) {
                            foldername = "SaleableStockImages";
                        } else if (finalList.get(i).contains("_visibility_img_")) {
                            foldername = "VisibilityImages";
                        } else if (finalList.get(i).contains("_ConsumerSimg_")) {
                            foldername = "ConsumerInteractionImages";
                        } else if (finalList.get(i).contains("_QuizPic-")) {
                            foldername = "MEAuditImages";
                        } else if (finalList.get(i).contains("_before_makeo_img_") || finalList.get(i).contains("_after_makeo_img_")) {
                            foldername = "MeMakeoverImages";
                        } else if (finalList.get(i).contains("SurveyPic-")) {
                            foldername = "SurveyImages";
                        } else if (finalList.get(i).contains("_invoiceimg_")) {
                            foldername = "ConsumerReturnImages";
                        } else if (finalList.get(i).contains("_minwordsimg_")) {
                            foldername = "InwardImages";
                        } else if (finalList.get(i).contains("-SkinGenius-")) {
                            foldername = "SkinGeniusImages";
                        } else if (finalList.get(i).contains("-CompOfferImg-") || finalList.get(i).contains("-Gwp_CompOfferImg-")) {
                            foldername = "CompetitionOffersImages";
                        } else if (finalList.get(i).contains("_GeoTag-")) {
                            foldername = "GeoTagImages";
                        } else if (finalList.get(i).contains("-Checkout_Selfie_img_") || finalList.get(i).contains("_CheckoutQuestionImg-") || finalList.get(i).contains("_CheckoutAnsImg-")) {
                            foldername = "CheckoutImages";
                        } else {
                            foldername = "BulkUpload";
                        }
                        filename = finalList.get(i);
                    }
                    break;
                }

                File originalFile = new File(CommonString.getImagesFolder(context) + filename);
                File finalFile = saveBitmapToFile(originalFile);
                if (finalFile == null) {
                    finalFile = originalFile;
                }


                String date = visit_date.replace("/", "");
                com.squareup.okhttp.OkHttpClient okHttpClient = new com.squareup.okhttp.OkHttpClient();
                okHttpClient.setConnectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS);
                okHttpClient.setWriteTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS);
                okHttpClient.setReadTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS);
                com.squareup.okhttp.RequestBody photo = com.squareup.okhttp.RequestBody.create(com.squareup.okhttp.MediaType.parse("application/octet-stream"), finalFile);
                com.squareup.okhttp.RequestBody body1 = new MultipartBuilder().type(MultipartBuilder.FORM)
                        .addFormDataPart("file", finalFile.getName(), photo).addFormDataPart("FolderName", foldername)
                        .addFormDataPart("Path", date).build();
                retrofit.Retrofit adapter = new retrofit.Retrofit.Builder().baseUrl(CommonString.URLGORIMAG).client(okHttpClient)
                        .addConverterFactory(new StringConverterFactory()).build();
                PostApiForUpload api = adapter.create(PostApiForUpload.class);
                retrofit.Call<String> call = api.getUploadImageRetrofitOne(body1);
                final File finalFile1 = finalFile;
                final String finalFilename = filename;
                call.enqueue(new retrofit.Callback<String>() {
                    @Override
                    public void onResponse(retrofit.Response<String> response) {
                        try {
                            Log.d("IMG_response", response.body() + " --- File_name ----" + finalFilename);
                            if (response.code() == 200 && response.message().equalsIgnoreCase("OK") && response.isSuccess() && response.body().contains("Success")) {
                                if (finalFilename.contains("_counter_img_two_") || finalFilename.contains("_counter_img_one_") || finalFilename.contains("_cp_img_one_") || finalFilename.contains("_cp_img_two_") || finalFilename.contains("_groomed_img_mrng_") || finalFilename.contains("_groomed_img_noon_") || finalFilename.contains("_groomed_img_evning_")) {
                                    db.open();
                                    db.insert_temp_image(finalFilename, visit_date);
                                } else {
                                    finalFile1.delete();
                                }
                                statusforimage[0] = 1;
                                uploadedFiles[0]++;
                            } else {
                                statusforimage[0] = 0;
                            }
                            if (statusforimage[0] == 0) {
                            } else {
                                UploadImageRecursive();
                            }
                        } catch (Exception e) {
                            Log.e("finalList", "Downloader"+e.toString());
                            e.fillInStackTrace();
                        } catch (OutOfMemoryError error) {
                            Log.e("finalList", "Downloader"+error.toString());
                            statusforimage[0] = -1;
                            error.fillInStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        Log.e("finalList", "Downloader"+t.toString());
                        if (t instanceof IOException || t instanceof SocketTimeoutException || t instanceof SocketException) {
                            statusforimage[0] = -1;
                        }
                    }
                });
            }
        } catch (Exception e) {
            Log.e("finalList", "Downloader"+e.toString());
            e.fillInStackTrace();
        }
    }

    public void upload_BaProfilewithaudit(String jsondata) {
        try {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), 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(Call<JsonObject> call, Response<JsonObject> response) {
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.updateBaProfileStatus(username, visit_date, CommonString.KEY_Y);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    }
                }

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

                }
            });

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

    public void upload_CounterProfile(String jsondata, final JourneyPlan object) {
        try {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), 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(Call<JsonObject> call, Response<JsonObject> response) {
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.updateCounterProfileStatus(username, visit_date, CommonString.KEY_Y);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    }
                }

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

                }
            });

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

    private void calculate_me_quiz_data(JourneyPlan jcp_Object, ArrayList<MEMEAuditQuestion> me_quizList) {
        try {
            if (me_quizList.size() > 0) {
                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("QuizId", me_quizList.get(k).getQuizId());
                    obj.put("UserId", me_quizList.get(k).getUser_Id());
                    obj.put("Question_Id", me_quizList.get(k).getQuestionId());
                    obj.put("Question_Type", me_quizList.get(k).getQuestionType());
                    JSONArray compArraymult = new JSONArray();
                    JSONObject objmultians = new JSONObject();
                    if (me_quizList.get(k).getQuestionType().equalsIgnoreCase("List Single Choice")) {
                        objmultians.put("Answer", me_quizList.get(k).getAnswer());
                        objmultians.put("Answer_Id", me_quizList.get(k).getAnswerId());
                        objmultians.put("Answer_Image", me_quizList.get(k).getStr_audit_img());
                        compArraymult.put(objmultians);
                    } else if (!me_quizList.get(k).getQuestionType().equalsIgnoreCase("List Multiple Choice")) {
                        objmultians.put("Answer", me_quizList.get(k).getAnswer());
                        objmultians.put("Answer_Id", 0);
                        objmultians.put("Answer_Image", "");
                        compArraymult.put(objmultians);
                    } else {
                        db.open();
                        ArrayList<MEMEAuditQuestion> multiansList = db.getquiz_answer(me_quizList.get(k).getKeyId());
                        if (multiansList.size() > 0) {
                            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();
                jsonObject.put("MID", jcp_Object.getMID());
                jsonObject.put("Keys", "ME_Quiz_Data");
                jsonObject.put("JsonData", consumerUserInfoArray.toString());
                jsonObject.put("UserId", username.toLowerCase());
                upload_ME_Quiz_Data(jsonObject.toString(), quizList);
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public void upload_ME_Quiz_Data(String jsondata, final ArrayList<MEMEAuditQuestion> me_quizList) {
        try {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), 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(Call<JsonObject> call, Response<JsonObject> response) {
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    // db.update_groomed_img(counter_id, visit_date, username);
                                    db.update_Me_Quiz(counter_id, username);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    }
                }

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

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

    private void calculate_retail_excellence_data(JourneyPlan jcp_Object, ArrayList<MasterRetailExcellence> masterRetailExcellenceArrayList) {
        try {
            if (masterRetailExcellenceArrayList.size() > 0) {
                JSONArray consumerUserInfoArray = new JSONArray();
                for (int k = 0; k < masterRetailExcellenceArrayList.size(); k++) {
                    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", masterRetailExcellenceArrayList.get(k).getItemCatId());
                    obj.put("ItemId", masterRetailExcellenceArrayList.get(k).getItemId());
                    if (masterRetailExcellenceArrayList.get(k).getAnswer().equalsIgnoreCase("Yes")) {
                        obj.put("Available", 1);
                    } else {
                        obj.put("Available", 0);
                    }
                    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());
                //test("retailjson",jsonObject.toString());
                upload_Retail_Excellence_Data(jsonObject.toString(), masterRetailExcellenceArrayList);
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public void upload_Retail_Excellence_Data(String jsondata, final ArrayList<MasterRetailExcellence> masterRetailExcellenceArrayList) {
        try {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), 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(Call<JsonObject> call, Response<JsonObject> response) {
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.update_retail_excellence(counter_id, username);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    }
                }

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

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

    private void calculate_me_sale_data(JourneyPlan jcp_Object, ArrayList<ProductMaster> productMasterArrayList) {
        try {
            if (productMasterArrayList.size() > 0) {
                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);
                    }
                }
                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());
                //  //test("salejson",jsonObject.toString());
                upload_ME_Sale_Data(jsonObject.toString(), productMasterArrayList);
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public void upload_ME_Sale_Data(String jsondata, final ArrayList<ProductMaster> productMasterArrayList) {
        try {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), 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(Call<JsonObject> call, Response<JsonObject> response) {
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.update_me_sale(counter_id, username);
                                    // db.update_groomed_img(counter_id, visit_date, username);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    }
                }

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

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


    private void calculate_me_makeoverdata(ArrayList<InvoiceGetterSetter> memakeoverList, int consumerIndex) {
        try {

            if (memakeoverList.size() > 0) {
                db.open();
                JourneyPlan jcp_Object = db.getBIDfromJCP(memakeoverList.get(consumerIndex).getStrUserId(), counter_id);
                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", memakeoverList.get(consumerIndex).getStrUserId());
                obj.put("TranId", memakeoverList.get(consumerIndex).getUnique_code());
                obj.put("ConsumerName", memakeoverList.get(consumerIndex).getCustomer_name());
                obj.put("MobileNumber", memakeoverList.get(consumerIndex).getMobile_no());
                obj.put("EmailId", memakeoverList.get(consumerIndex).getConsumer_email_Id());
                obj.put("Age", memakeoverList.get(consumerIndex).getConsumer_age());
                obj.put("SkinType", memakeoverList.get(consumerIndex).getConsumer_skinType());
                obj.put("Look", memakeoverList.get(consumerIndex).getLook_creater_str());
                obj.put("Gender", memakeoverList.get(consumerIndex).getCustomer_gender());
                obj.put("BeforeMakeoverImg", memakeoverList.get(consumerIndex).getBefore_makeover_img());
                obj.put("AfterMakeoverImg", memakeoverList.get(consumerIndex).getAfter_makeover_img());
                obj.put("Feedback", memakeoverList.get(consumerIndex).getCst_feed_back_value());
                obj.put("TermConditions", memakeoverList.get(consumerIndex).getStr_termcondition());
                consumerUserInfoArray.put(obj);

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("MID", jcp_Object.getMID());
                jsonObject.put("Keys", "ME_Makeover_Capture");
                jsonObject.put("JsonData", consumerUserInfoArray.toString());
                jsonObject.put("UserId", memakeoverList.get(consumerIndex).getStrUserId());
                upload_Me_Makeover_Data(jsonObject.toString(), memakeoverList.get(consumerIndex), consumerIndex);
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public void upload_Me_Makeover_Data(String jsondata, final InvoiceGetterSetter object, final int index) {
        try {
            final int[] finalJsonIndex = {index};
            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(Call<JsonObject> call, Response<JsonObject> response) {
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.update_makeover(counter_id, object.getStrUserId(), object.getKeyId(), false);
                                    db.updateMasterTransactionDataStatus(object.getUnique_code());
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != me_makeoverList.size()) {
                                        calculate_me_makeoverdata(me_makeoverList, finalJsonIndex[0]);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    }
                }

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

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

    private void calculate_me_counter_imgage_data(JourneyPlan ba_counter_imgObject) {
        try {
            JourneyPlan jcpfor_bid = db.getBIDfromJCP(username, counter_id);
            JSONArray promoArray = new JSONArray();
            JSONObject obj = new JSONObject();
            obj.put("MID", jcpfor_bid.getMID());
            obj.put("UserId", username);
            obj.put("VisitDate", visit_date);
            obj.put("PreSetUpImgOne", ba_counter_imgObject.getPresetup_img_one_str());
            obj.put("PreSetUpImgTwo", ba_counter_imgObject.getPresetup_img_two_str());
            obj.put("PostSetUpImgOne", ba_counter_imgObject.getPostsetup_img_one_str());
            obj.put("PostSetUpImgTwo", ba_counter_imgObject.getPostsetup_img_two_str());
            promoArray.put(obj);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("MID", jcpfor_bid.getMID());
            jsonObject.put("Keys", "ME_Counter_Image_Data");
            jsonObject.put("JsonData", promoArray.toString());
            jsonObject.put("UserId", username);
            upload_ba_counter_img(jsonObject.toString(), ba_counter_imgObject);
        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }
}