package com.cpm.lorealbaautomation.retrofit;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.view.WindowManager;

import androidx.annotation.NonNull;

import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.google.gson.Gson;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gettersetter.ReferenceVariablesForDownloadActivity;
import com.cpm.lorealbaautomation.gsonGetterSetter.BaListGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.JCPGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBAProfileGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterInvoiceTypeGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReasonGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonVisibilityGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileQuestionGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromoOffer;
import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult;
import com.cpm.lorealbaautomation.gsonGetterSetter.ServerTimeGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.TCounterInvoiceGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.TStockSummaryGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.TableStructure;
import com.cpm.lorealbaautomation.gsonGetterSetter.TableStructureGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.testerreports.TesterCounter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
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;

/**
 * Created by jeevanp on 15-12-2017.
 */

public class DownloadAllDatawithRetro extends ReferenceVariablesForDownloadActivity {
    boolean isvalid;
    private Retrofit adapter;
    Context context;
    public int listSize = 0;
    int status = 0;
    Lorealba_Database db;
    ProgressDialog pd;
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    String date, counterId = "";
    int from;

    public DownloadAllDatawithRetro(Context context) {
        this.context = context;
    }

    public DownloadAllDatawithRetro(Context context, Lorealba_Database db, ProgressDialog pd, int from) {
        this.context = context;
        this.db = db;
        this.pd = pd;
       preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        date = preferences.getString(CommonString.KEY_DATE, "");
        counterId = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        this.from = from;
        db.open();
    }


    public void downloadDataUniversalWithoutWait(final ArrayList<String> jsonStringList, final ArrayList<String> KeyNames, int downloadindex, int type) {
        status = 0;
        isvalid = false;
        final String[] data_global = {""};
        String jsonString = "", KeyName = "";
        int jsonIndex = 0;
        if (!jsonStringList.isEmpty()) {
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            jsonString = jsonStringList.get(downloadindex);
            KeyName = KeyNames.get(downloadindex);
            jsonIndex = downloadindex;
            pd.setMessage("Downloading (" + downloadindex + "/" + listSize + ") \n" + KeyName);
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString);
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<String> call = api.getDownloadAll(jsonData);
            final int[] finalJsonIndex = {jsonIndex};
            final String finalKeyName = KeyName;

            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                    String responseBody = response.body();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body();
                            assert data != null;
                            if (data.isEmpty()) {
                                data_global[0] = "";
                            } else {
                                data_global[0] = data;
                                if (finalKeyName.equalsIgnoreCase("Table_Structure")) {
                                    editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]);
                                    editor.apply();
                                    tableStructureObj = new Gson().fromJson(data, TableStructureGetterSetter.class);
                                    String isAllTableCreated = createTable(tableStructureObj);

                                    if (isAllTableCreated != CommonString.KEY_SUCCESS) {
                                        AlertandMessages.showAlert((Activity) context, isAllTableCreated + " not created", true);
                                        pd.dismiss();
                                    }
                                } else {
                                    editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]);
                                    editor.apply();
                                    new MyLoader(context, finalKeyName, data).execute();
                                }
                            }

                            finalJsonIndex[0]++;
                            if (finalJsonIndex[0] != KeyNames.size()) {
                                editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]);
                                editor.apply();
                                downloadDataUniversalWithoutWait(jsonStringList, KeyNames, finalJsonIndex[0], CommonString.DOWNLOAD_ALL_SERVICE);
                            } else {
                                editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, 0);
                                editor.apply();
                                pd.setMessage("Downloading Images");
                                new DownloadImageTask(context, masterPromoOfferObject, baListObject).execute();
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]);
                            editor.apply();
                            pd.dismiss();
                            AlertandMessages.showAlert((Activity) context, finalKeyName + " Data not found ", true);
                        }
                    } else {
                        editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]);
                        editor.apply();
                        pd.dismiss();
                        AlertandMessages.showAlert((Activity) context, "Error in downloading Data at " + finalKeyName, true);
                    }
                }

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                    isvalid = true;
                    pd.dismiss();
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE, true);
                }
            });
        } else {
            editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, 0);
            editor.apply();
            pd.setMessage("Downloading Images");
            new DownloadImageTask(context, masterPromoOfferObject, baListObject).execute();
        }
    }

    String createTable(TableStructureGetterSetter tableGetSet) {
        List<TableStructure> tableList = tableGetSet.getTableStructure();
        try {
            for (int i = 0; i < tableList.size(); i++) {
                String table = tableList.get(i).getSqlText();
                db.open();
                if (db.createtable(table) == 0) {
                    return table;
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return CommonString.KEY_SUCCESS;
    }

    public String downloadDataUniversal(final String jsonString, int type) {
        try {
            status = 0;
            isvalid = false;
            final String[] data_global = {""};
            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);
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<ResponseBody> call = null;
            if (type == CommonString.CHANGE_PASSWORD_SERVICE) {
                call = api.getChangePassword(jsonData);
            } else if (type == CommonString.FORGOT_PASSWORD_SERVICE) {
                call = api.getResetPassword(jsonData);
            }
            assert call != null;
            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.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                data_global[0] = data;
                                isvalid = true;
                                status = 1;
                            } else {
                                data_global[0] = data;
                                isvalid = true;
                                status = 1;
                            }

                        } catch (Exception e) {
                            e.fillInStackTrace();
                            isvalid = true;
                            status = -2;
                        }
                    } else {
                        isvalid = true;
                        status = -1;
                    }
                }

                @Override
                public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                    isvalid = true;
                    if (t instanceof SocketTimeoutException) {
                        status = 3;
                    } else if (t instanceof IOException) {
                        status = 3;
                    } else {
                        status = 3;
                    }
                }
            });

            while (!isvalid) {
                synchronized (this) {
                    this.wait(25);
                }
            }
            if (isvalid) {
                synchronized (this) {
                    this.notify();
                }
            }
            if (status == 1) {
                return data_global[0];
            } else if (status == 2) {
                return CommonString.MESSAGE_NO_RESPONSE_SERVER;
            } else if (status == 3) {
                return CommonString.MESSAGE_SOCKETEXCEPTION;
            } else if (status == -2) {
                return CommonString.MESSAGE_INVALID_JSON;
            } else {
                return CommonString.KEY_FAILURE;
            }
        } catch (Exception e) {
            e.fillInStackTrace();
            return CommonString.KEY_FAILURE;
        }
    }


    @SuppressLint("StaticFieldLeak")
    private class MyLoader extends AsyncTask<String, String, String> {
        Context context;
        String data, finalKeyName;

        public MyLoader(Context context, String finalKeyName, String data) {
            this.context = (context);
            this.data = data;
            this.finalKeyName = finalKeyName;
        }

        @Override
        protected String doInBackground(String... strings) {
            //perform heavy task here and finally update the UI with result this way -
            try {
                //test("Json_data", data);
                switch (finalKeyName) {
                    case "BA_List":
                        if (!data.contains("No Data")) {
                            baListObject = new Gson().fromJson(data, JCPGetterSetter.class);
                            db.open();
                            if (baListObject != null && !db.insertBalistData(baListObject)) {
                                AlertandMessages.showToastMsg(context, "Ba List data not saved");
                                pd.dismiss();
                            }
                        } else {
                            throw new java.lang.Exception();
                        }
                        break;

                    case "D2D_ARS":
                        if (!data.contains("No Data")) {
                            d2DARSGetterSetter = new Gson().fromJson(data, JCPGetterSetter.class);
                            db.open();
                            if (d2DARSGetterSetter != null && !d2DARSGetterSetter.getD2DArsList().isEmpty()) {
                                editor = preferences.edit();
                                editor.putString(CommonString.KEY_D2D_ARS_URL, d2DARSGetterSetter.getD2DArsList().get(0).getD2d_ars_url());
                                editor.commit();
                            } else {
                                editor = preferences.edit();
                                editor.putString(CommonString.KEY_D2D_ARS_URL, "");
                                editor.commit();
                            }
                        }
                        break;

                    case "Mapping_JourneyPlan":
                        if (!data.contains("No Data")) {
                            jcpObject = new Gson().fromJson(data, JCPGetterSetter.class);
                            db.open();
                            if (jcpObject != null && !db.insertJCPData(jcpObject)) {
                                AlertandMessages.showToastMsg(context, "JCP data not saved");
                                pd.dismiss();
                            }
                        } else {
                            throw new java.lang.Exception();
                        }
                        break;

                    case "Mapping_CounterGroup_Brand":
                        if (!data.contains("No Data")) {
                            mappingCounterGroupBrandObject = new Gson().fromJson(data, JCPGetterSetter.class);
                            db.open();
                            if (mappingCounterGroupBrandObject != null && !db.insertmappingcountergroupBrand(mappingCounterGroupBrandObject)) {
                                AlertandMessages.showToastMsg(context, "Mapping_CounterGroup_Brand data not saved");
                                pd.dismiss();
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Mapping_CounterGroup_Brand");
                        }

                        break;

                    case "Product_Master":
                        if (!data.contains("No Data")) {
                            product_masterObject = new Gson().fromJson(data, TableStructureGetterSetter.class);
                            db.open();
                            if (product_masterObject != null && !db.insertproductmasterdata(product_masterObject)) {
                                AlertandMessages.showToastMsg(context, "Product Master data not saved");
                                pd.dismiss();
                            }
                        } else {
                            throw new java.lang.Exception();
                        }

                        break;

                    case "SkinGeniusUrl":
                        if (!data.contains("No Data")) {
                            SkinGeniusUrlObject = new Gson().fromJson(data, TableStructureGetterSetter.class);
                            db.open();
                            if (SkinGeniusUrlObject != null && !SkinGeniusUrlObject.getSkinGeniusUrl().isEmpty()) {
                                editor = preferences.edit();
                                editor.putString(CommonString.KEY_SKIN_GENIUS_URL, SkinGeniusUrlObject.getSkinGeniusUrl().get(0).getSkinGeniusUrl());
                                editor.commit();
                            } else {
                                editor = preferences.edit();
                                editor.putString(CommonString.KEY_SKIN_GENIUS_URL, "");
                                editor.commit();
                            }

                            if (SkinGeniusUrlObject != null && !SkinGeniusUrlObject.getSkinGeniusUrl().isEmpty()) {
                                editor = preferences.edit();
                                editor.putString(CommonString.KEY_SKIN_MAYBELLINE_URL, SkinGeniusUrlObject.getSkinGeniusUrl().get(0).getMaybellineUrl());
                                editor.commit();
                            } else {
                                editor = preferences.edit();
                                editor.putString(CommonString.KEY_SKIN_MAYBELLINE_URL, "");
                                editor.commit();
                            }
                        }
                        break;
                    case "Mapping_Visibility":
                        if (!data.contains("No Data")) {
                            mapping_visibilityObject = new Gson().fromJson(data, TableStructureGetterSetter.class);
                            db.open();
                            if (mapping_visibilityObject != null && !db.insertmappingvisibility(mapping_visibilityObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Mapping_Visibility data not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Mapping_Visibility");
                        }

                        break;

                    case "Master_Posm":
                        if (!data.contains("No Data")) {
                            posmmasterObject = new Gson().fromJson(data, TableStructureGetterSetter.class);
                            db.open();
                            if (posmmasterObject != null && !db.insertmappingposmdata(posmmasterObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_Posm data not saved");
                            }
                        }

                        break;


                    case "InwardSales_PO":
                        if (!data.contains("No Data")) {
                            inwardSales_POObject = new Gson().fromJson(data, TableStructureGetterSetter.class);
                            db.open();
                            if (inwardSales_POObject != null && !db.insertInwordSalesPoData(inwardSales_POObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "InwardSales PO Data not saved");
                            }
                        }


                        break;


                    case "ServerTime":
                        if (!data.contains("No Data")) {
                            serverTimeObj = new Gson().fromJson(data, ServerTimeGetterSetter.class);
                            if (serverTimeObj != null && !db.insertServerTimeData(serverTimeObj)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "ServerTime not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("ServerTime");
                        }

                        break;

                    case "StockSummary_Check":
                        if (!data.contains("No Data")) {
                            tStockSummaryCheckObj = new Gson().fromJson(data, ServerTimeGetterSetter.class);
                            if (tStockSummaryCheckObj != null && !db.insertTStockSummaryCheck(tStockSummaryCheckObj)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "StockSummary_Check not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("StockSummary_Check");
                        }
                        break;

                    case "T_StockSummary":
                        if (!data.contains("No Data")) {
                            try {
                                tStockSummaryObj = new Gson().fromJson(data, TStockSummaryGetterSetter.class);
                                if (tStockSummaryObj != null) {
                                    editor = preferences.edit();
                                    editor.putInt(CommonString.KEY_INCORRECT_TSTOCK_SUMMERY + date, 0);
                                    editor.apply();
                                    db.open();
                                    if (!db.insertTStockSummaryData(tStockSummaryObj, counterId, date)) {
                                        db.delete_table_data("T_StockSummary");
                                        AlertandMessages.showToastMsg(context, "T_StockSummary not saved");
                                    } else {
                                        throw new java.lang.Exception();
                                    }
                                }
                            } catch (Exception e) {
                                throw new java.lang.Exception();
                            }
                        }

                        break;

                    case "T_CounterInvoice":
                        if (!data.contains("No Data")) {
                            tCounterInvoiceObj = new Gson().fromJson(data, TCounterInvoiceGetterSetter.class);
                            db.open();
                            if (tCounterInvoiceObj != null && !db.insertTCounterInvoiceData(tCounterInvoiceObj)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "T_CounterInvoice not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("T_CounterInvoice");
                        }


                        break;

                    case "Master_NonVisibility":
                        if (!data.contains("No Data")) {
                            masterNonVisibilityGetterSetter = new Gson().fromJson(data, MasterNonVisibilityGetterSetter.class);
                            db.open();
                            if (masterNonVisibilityGetterSetter != null && !db.insertMasterNonVisibilityData(masterNonVisibilityGetterSetter)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_NonVisibility not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_NonVisibility");
                        }


                        break;


                    case "Master_NonStockReason":
                        if (!data.contains("No Data")) {
                            masterNonStockReasonObj = new Gson().fromJson(data, MasterNonStockReasonGetterSetter.class);
                            db.open();
                            if (masterNonStockReasonObj != null && !db.insertNonStockReasonData(masterNonStockReasonObj)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_NonStockReason not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_NonStockReason");
                        }


                        break;
                    //jp
                    case "Master_SkinType":
                        if (!data.contains("No Data")) {
                            masterSkinTypeObject = new Gson().fromJson(data, TableStructureGetterSetter.class);
                            db.open();
                            if (masterSkinTypeObject != null && !db.insertSkinTypeMaster(masterSkinTypeObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_SkinType not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }

                        break;

                    case "Master_AgeLimit":
                        if (!data.contains("No Data")) {
                            masterAgeLimitObject = new Gson().fromJson(data, TableStructureGetterSetter.class);
                            db.open();
                            if (masterAgeLimitObject != null && !db.insertAgeLimitMaster(masterAgeLimitObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_AgeLimit not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }

                        break;

                    case "Master_Profile":
                        if (!data.contains("No Data")) {
                            masterProfileGetterSetter = new Gson().fromJson(data, MasterProfileGetterSetter.class);
                            db.open();
                            if (masterProfileGetterSetter != null && !db.insertMasterProfile(masterProfileGetterSetter)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_Profile not saved");
                            }
                        }


                        break;
                    case "Master_ProfileQuestion":
                        if (!data.contains("No Data")) {
                            masterProfileQuestionGetterSetter = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (masterProfileQuestionGetterSetter != null && !db.insertMasterProfileQuestion(masterProfileQuestionGetterSetter)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_AgeLimit not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }

                        break;

                    case "Master_ReturnReason":
                        if (!data.contains("No Data")) {
                            return_ReasonObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (return_ReasonObject != null && !db.insert_return_reason(return_ReasonObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_ReturnReason not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }


                        break;


                    case "Master_TermsCondition":
                        if (!data.contains("No Data")) {
                            termConditionObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (termConditionObject != null && !db.inserterm_condition(termConditionObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_TermsCondition not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }

                        break;

                    case "Master_InvoiceType":
                        if (!data.contains("No Data")) {
                            masterInvoiceTypeObj = new Gson().fromJson(data, MasterInvoiceTypeGetterSetter.class);
                            db.open();
                            if (masterInvoiceTypeObj != null && !db.insertInvoiceTypeMasterData(masterInvoiceTypeObj)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_InvoiceType not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }


                        break;

                    case "T_LeaveRequest":
                        if (!data.contains("No Data")) {
                            LeaveRequestObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (LeaveRequestObject != null && !db.insertLeaveRequest(LeaveRequestObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "T_LeaveRequest not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("T_LeaveRequest");
                        }


                        break;


                    case "T_LeaveLedger":
                        if (!data.contains("No Data")) {
                            leaveStatusObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (leaveStatusObject != null && !db.insert_leave_status(leaveStatusObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "T_LeaveLedger not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("T_LeaveLedger");
                        }

                        break;

                    case "Master_Break":
                        if (!data.contains("No Data")) {
                            masterBreakObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (masterBreakObject != null && !db.insert_master_break(masterBreakObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_Break not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }


                        break;


                    ///jp_download Report
                    case "Report_SalesValue":
                        if (!data.contains("No Data")) {
                            editor = preferences.edit();
                            editor.putString(CommonString.KEY_DASHBOARD_REFRESH_TIME, CommonFunctions.getCurrentTime_only());
                            editor.commit();
                            reportSaleValueObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (reportSaleValueObject != null && !db.insertReportSaleValue(reportSaleValueObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_SalesValue not saved");
                            }
                        } else {
                            editor = preferences.edit();
                            editor.putString(CommonString.KEY_DASHBOARD_REFRESH_TIME, CommonFunctions.getCurrentTime_only());
                            editor.commit();
                            db.open();
                            db.delete_table_data("Report_SalesValue");
                        }

                        break;

                    ///jp_download Report
                    case "Report_Sales_Detail":
                        if (!data.contains("No Data")) {
                            reportSaleDetailsObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (reportSaleDetailsObject != null && !db.insertReportSaleDetails(reportSaleDetailsObject, false)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_Sales_Detail not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_Sales_Detail");
                        }
                        break;

                    case "Report_Sales_DetailME":
                        if (!data.contains("No Data")) {
                            reportSaleDetailsObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (reportSaleDetailsObject != null && !db.insertReportSaleDetails(reportSaleDetailsObject, true)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_Sales_DetailME not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_Sales_DetailME");
                        }
                        break;

                    case "Report_AvgTransactionPerDay":
                        if (!data.contains("No Data")) {
                            reportavGTransationValueObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (reportavGTransationValueObject != null && !db.insertReportAvgTransationperDay(reportavGTransationValueObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_AvgTransactionPerDay not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_AvgTransactionPerDay");
                        }


                        break;

                    case "Report_AvgUnitsPerBill":
                        if (!data.contains("No Data")) {
                            reportAvgUnitPerBillObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (reportAvgUnitPerBillObject != null && !db.insertReportAvgPerBillDay(reportAvgUnitPerBillObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_AvgUnitsPerBill not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_AvgUnitsPerBill");
                        }


                        break;

                    case "Report_AvgBillValue":
                        if (!data.contains("No Data")) {
                            reportAvgBillUnitObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (reportAvgBillUnitObject != null && !db.insertReportAvgBillUnit(reportAvgBillUnitObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_AvgBillValue not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_AvgBillValue");
                        }


                        break;

                    case "Report_AvgLinPerBill":
                        if (!data.contains("No Data")) {
                            reportAvgLinPerBillObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (reportAvgLinPerBillObject != null && !db.insertReportAvgLinPerBill(reportAvgLinPerBillObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_AvgLinPerBill not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_AvgLinPerBill");
                        }


                        break;

                    case "Report_SellingPrice":
                        if (!data.contains("No Data")) {
                            reportSalingPrizeObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (reportSalingPrizeObject != null && !db.insertReportSelingPrice(reportSalingPrizeObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_SellingPrice not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_SellingPrice");
                        }


                        break;

                    case "Report_Top10Volume":
                        if (!data.contains("No Data")) {
                            reportTop10VolumeObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (reportTop10VolumeObject != null && !db.insertReportTop10Volume(reportTop10VolumeObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_Top10Volume not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_Top10Volume");
                        }


                        break;

                    case "Report_Top10Value":
                        if (!data.contains("No Data")) {
                            reportTop10ValueObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (reportTop10ValueObject != null && !db.insertReportTop10Value(reportTop10ValueObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_Top10Value not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_Top10Value");
                        }

                        break;
                    case "Report_ME_Sale":
                        if (!data.contains("No Data")) {
                            reportMeSale = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                            db.open();
                            if (reportMeSale != null && !db.insertMeSaleReport(reportMeSale)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_ME_Sale not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_ME_Sale");
                        }

                        break;

                    case "Master_BAProfile":
                        if (!data.contains("No Data")) {
                            masterBAProfileGetterSetter = new Gson().fromJson(data, MasterBAProfileGetterSetter.class);
                            db.open();
                            if (masterBAProfileGetterSetter != null && !db.insertBaProfileValue(masterBAProfileGetterSetter)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_BAProfile not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_BAProfile");
                        }


                        break;
                    case "Master_PromoOffers":
                        if (!data.contains("No Data")) {
                            masterPromoOfferObject = new Gson().fromJson(data, MasterBAProfileGetterSetter.class);
                            db.open();
                            if (masterPromoOfferObject != null && !db.insertPromoOffers(masterPromoOfferObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_PromoOffers not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_PromoOffers");
                        }

                        break;

                    case "Report_AttendanceDetail":
                        if (!data.contains("No Data")) {
                            reportAttendenceDetailGetterSetter = new Gson().fromJson(data, MasterBAProfileGetterSetter.class);
                            db.open();
                            if (reportAttendenceDetailGetterSetter != null && !db.insertreport_attendence_details(reportAttendenceDetailGetterSetter)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_AttendanceDetail not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_AttendanceDetail");
                        }


                        break;
                    case "Report_AttendanceSummary":
                        if (!data.contains("No Data")) {
                            reportAttendenceSummeryGetterSetter = new Gson().fromJson(data, MasterBAProfileGetterSetter.class);
                            db.open();
                            if (reportAttendenceSummeryGetterSetter != null && !db.insertreport_attendence_summery(reportAttendenceSummeryGetterSetter)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_AttendanceSummary not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_AttendanceSummary");
                        }

                        break;

                    case "Report_InwardStockSummary":
                        if (!data.contains("No Data")) {
                            reportInwordStockSummeryGetterSetter = new Gson().fromJson(data, MasterBAProfileGetterSetter.class);
                            db.open();
                            if (reportInwordStockSummeryGetterSetter != null && !db.insertreport_inword_stock_summery(reportInwordStockSummeryGetterSetter)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_InwardStockSummary not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_InwardStockSummary");
                        }


                        break;

                    case "Report_BA_Availability":
                        if (!data.contains("No Data")) {
                            reportbaAvailabilityGetterSetter = new Gson().fromJson(data, MasterBAProfileGetterSetter.class);
                            db.open();
                            if (reportbaAvailabilityGetterSetter != null && !db.insert_ba_availability(reportbaAvailabilityGetterSetter)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_BA_Availability not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_BA_Availability");
                        }


                        break;

                    case "Master_Looks":
                        if (!data.contains("No Data")) {
                            masterLookObject = new Gson().fromJson(data, MasterBAProfileGetterSetter.class);
                            db.open();
                            if (masterLookObject != null && !db.insert_master_look(masterLookObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_Looks not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_Looks");
                        }

                        break;

                    case "ME_MEAuditQuestion":
                        if (!data.contains("No Data")) {
                            meAuditMasterObject = new Gson().fromJson(data, MasterBAProfileGetterSetter.class);
                            db.open();
                            if (meAuditMasterObject != null && !db.insert_me_audit_question(meAuditMasterObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "ME_MEAuditQuestion not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("ME_MEAuditQuestion");
                        }


                        break;

                    case "ME_MEAuditQuestion_UploadStatus":
                        if (!data.contains("No Data")) {
                            meAuditMasterUploadStatusObject = new Gson().fromJson(data, MasterBAProfileGetterSetter.class);
                            db.open();
                            if (meAuditMasterUploadStatusObject != null && !db.insert_me_quizuploadstatus(meAuditMasterUploadStatusObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "ME_MEAuditQuestion_UploadStatus not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("ME_MEAuditQuestion_UploadStatus");
                        }

                        break;

                    case "Master_Promotion":
                        if (!data.contains("No Data")) {
                            responseResult = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (responseResult != null && !db.insertPromotionMaster(responseResult)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_Promotion not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_Promotion");
                        }

                        break;

                    case "Master_PromotionSetEntityItem":
                        if (!data.contains("No Data")) {
                            resultPromotionSetEntityItem = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (resultPromotionSetEntityItem != null && !db.insertPromotionSetEntityItemMaster(resultPromotionSetEntityItem)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_PromotionSetEntityItem not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_PromotionSetEntityItem");
                        }

                        break;

                    case "Master_PromotionGetEntityItem":
                        if (!data.contains("No Data")) {
                            resultPromotionGetEntityItem = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (resultPromotionGetEntityItem != null && !db.insertPromotionGetEntityItemMaster(resultPromotionGetEntityItem)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_PromotionGetEntityItem not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_PromotionGetEntityItem");
                        }

                        break;

                    case "Master_PromotionSetProductGroup":
                        if (!data.contains("No Data")) {
                            resultPromotionSetProductGroup = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (resultPromotionSetProductGroup != null && !db.insertPromotionSetProductGroupMaster(resultPromotionSetProductGroup)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_PromotionSetProductGroup not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_PromotionSetProductGroup");
                        }

                        break;

                    case "Master_PromotionGetProductGroup":
                        if (!data.contains("No Data")) {
                            resultPromotionGetProductGroup = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (resultPromotionGetProductGroup != null && !db.insertPromotionGetProductGroupMaster(resultPromotionGetProductGroup)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_PromotionGetProductGroup not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_PromotionGetProductGroup");
                        }

                        break;

                    case "Master_PromotionSetProductCatalog":
                        if (!data.contains("No Data")) {
                            promosetproductCatologObject = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (promosetproductCatologObject != null && !db.insertMasterPromotionSetProductCatalog(promosetproductCatologObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_PromotionSetProductCatalog not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_PromotionSetProductCatalog");
                        }

                        break;

                    case "Master_PromotionGetProductCatalog":
                        if (!data.contains("No Data")) {
                            promogetproductCatologObject = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (promogetproductCatologObject != null && !db.insertMasterPromotionGetProductCatalog(promogetproductCatologObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_PromotionGetProductCatalog not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_PromotionGetProductCatalog");
                        }

                        break;


                    case "Master_Survey":
                        if (!data.contains("No Data")) {
                            masterSurvey = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (masterSurvey != null && !db.insertMasterSurvey(masterSurvey)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_Survey not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_Survey");
                        }

                        break;

                    case "Master_LeaveType":
                        if (!data.contains("No Data")) {
                            masterLeaveType = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (masterLeaveType != null && !db.insertMasterLeaveType(masterLeaveType)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_LeaveType not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_LeaveType");
                        }

                        break;


                    case "Damage_ReturnToDistributor":
                        if (!data.contains("No Data")) {
                            damagedReturnToDistributorObject = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (damagedReturnToDistributorObject != null && !db.insertdamagedReturnToDistributor(damagedReturnToDistributorObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Damage_ReturnToDistributor not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Damage_ReturnToDistributor");
                        }

                        break;

                    case "Master_Survey_UploadStatus":
                        if (!data.contains("No Data")) {
                            baorcounterUploadStatusObject = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (baorcounterUploadStatusObject != null && !db.insertbaservaystusupload(baorcounterUploadStatusObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_Survey_UploadStatus not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_Survey_UploadStatus");
                        }

                        break;

                    case "Report_ProductGroupWiseSalesValue":
                        if (!data.contains("No Data")) {
                            productGroupwiseSaleObject = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (productGroupwiseSaleObject != null && !db.insertGroupWiseSale(productGroupwiseSaleObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_ProductGroupWiseSalesValue not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_ProductGroupWiseSalesValue");
                        }


                        break;

                    case "Report_SalesDateWise":
                        if (!data.contains("No Data")) {
                            reportsaleDatewiseObject = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (reportsaleDatewiseObject != null && !db.insertReportDaywiseSale(reportsaleDatewiseObject, false)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_SalesDateWise not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_SalesDateWise");
                        }

                        break;

                    case "Report_SalesDateWiseME":
                        if (!data.contains("No Data")) {
                            reportsaleDatewiseObject = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (reportsaleDatewiseObject != null && !db.insertReportDaywiseSale(reportsaleDatewiseObject, true)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_SalesDateWiseME not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_SalesDateWiseME");
                        }

                        break;

                    case "Damage_PreviousPending":
                        if (!data.contains("No Data")) {
                            damagedpendingObject = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (damagedpendingObject != null && !db.insertDamagedPending(damagedpendingObject)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Damage_PreviousPending not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Damage_PreviousPending");
                        }


                        break;

                    case "Report_SalesL3MValue":
                        if (!data.contains("No Data")) {
                            reportlastmonth = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (reportlastmonth != null && !db.insertreportsalemonth(reportlastmonth, false)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_SalesL3MValue not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_SalesL3MValue");
                        }

                        break;

                    case "Report_SalesL3MValueME":
                        if (!data.contains("No Data")) {
                            reportlastmonth = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (reportlastmonth != null && !db.insertreportsalemonth(reportlastmonth, true)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_SalesL3MValueME not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_SalesL3MValueME");
                        }

                        break;

                    case "Report_MTD_WorkingCounterME":
                        if (!data.contains("No Data")) {
                            reportlastmonth = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (reportlastmonth != null && !db.insertMeWorkingcounterDetails(reportlastmonth)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_MTD_WorkingCounterME not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_MTD_WorkingCounterME");
                        }

                        break;

                    case "Master_PromotionGetExclusionList":
                        if (!data.contains("No Data")) {
                            promogetexclusionlistob = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (promogetexclusionlistob != null && !db.insertpromogetexclusion(promogetexclusionlistob)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_PromotionGetExclusionList not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_PromotionGetExclusionList");
                        }

                        break;

                    case "Master_PromotionSetExclusionList":
                        if (!data.contains("No Data")) {
                            promosetexclusionlistob = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (promosetexclusionlistob != null && !db.insertpromosetExclusion(promosetexclusionlistob)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_PromotionSetExclusionList not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_PromotionSetExclusionList");
                        }

                        break;

                    case "Report_DamageStockHistory":
                        if (!data.contains("No Data")) {
                            reportdamagehistory = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (reportdamagehistory != null && !db.insertdamagestockhistory(reportdamagehistory)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_DamageStockHistory not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_DamageStockHistory");
                        }

                        break;

                    case "Master_SourcesOfSales":
                        if (!data.contains("No Data")) {
                            mastersourceofsales = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (mastersourceofsales != null && !db.insertsourceofsales(mastersourceofsales)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_SourcesOfSales not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }

                        break;

                    ////Updated by J.P 22/05/22
                    case "Master_CompetitonBrandWiseNuance":
                        if (!data.contains("No Data")) {
                            masterCompetitonBrandWiseNuance = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (masterCompetitonBrandWiseNuance != null && !db.insertMasterCompetitonBrandWiseNuance(masterCompetitonBrandWiseNuance)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_CompetitonBrandWiseNuance not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }

                        break;

                    case "Master_CompetitionOfferSet":
                        if (!data.contains("No Data")) {
                            masterCompetitionOfferSet = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (masterCompetitionOfferSet != null && !db.insertMasterCompetitionOfferSet(masterCompetitionOfferSet)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_CompetitionOfferSet not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }

                        break;

                    case "Master_CompetitionOffer":
                        if (!data.contains("No Data")) {
                            masterCompetitionOffer = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (masterCompetitionOffer != null && !db.insertMasterCompetitionOffer(masterCompetitionOffer)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_CompetitionOffer not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }
                        break;

                    case "Master_CompetitionOfferSaleRange":
                        if (!data.contains("No Data")) {
                            masterCompetitionOfferSaleRange = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (masterCompetitionOfferSaleRange != null && !db.insertMasterCompetitionOfferSaleRange(masterCompetitionOfferSaleRange)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_CompetitionOfferSaleRange not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }
                        break;

                    case "Master_RetailExcellence_Item":
                        if (!data.contains("No Data")) {
                            masterRetailExcellence = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (masterRetailExcellence != null && !db.insertMasterRetailExcellence(masterRetailExcellence)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_RetailExcellence_Item not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }
                        break;

                    case "Master_CompetitionOfferGet":
                        if (!data.contains("No Data")) {
                            masterCompetitionOfferGet = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (masterCompetitionOfferGet != null && !db.insertMasterCompetitionOfferGet(masterCompetitionOfferGet)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_CompetitionOfferGet not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }

                        break;

                    case "Master_CompetitionPromoType":
                        if (!data.contains("No Data")) {
                            masterCompetitionPromoType = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (masterCompetitionPromoType != null && !db.insertMasterCompetitionPromoType(masterCompetitionPromoType)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_CompetitionPromoType not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }

                        break;

                    case "Master_CompetitionProductType":
                        if (!data.contains("No Data")) {
                            masterCompetitionProductType = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (masterCompetitionProductType != null && !db.insertMasterCompProductType(masterCompetitionProductType)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_CompetitionProductType not saved");
                            }
                        } else {
                            throw new java.lang.Exception();
                        }

                        break;

                    case "AppDashboard_TVA":
                        if (!data.contains("No Data")) {
                            ResponseResult appDashTVA = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (appDashTVA != null && !db.insertDashTVA(appDashTVA)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "AppDashboard_TVA not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("AppDashboard_TVA");
                        }
                        break;

                    case "AppDashboard_TVADrillDown":
                        if (!data.contains("No Data")) {
                            ResponseResult appDashTVAdrillDown = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (appDashTVAdrillDown != null && !db.insertDashTVADrillDown(appDashTVAdrillDown)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "AppDashboard_TVADrillDown not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("AppDashboard_TVADrillDown");
                        }

                        break;

                    case "AppDashboard_LeaderBoard":
                        if (!data.contains("No Data")) {
                            ResponseResult leaderBoard = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (leaderBoard != null && !db.insertDashLeaderBoard(leaderBoard)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "AppDashboard_LeaderBoard not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("AppDashboard_LeaderBoard");
                        }

                        break;

                    case "AppDashboard_Incentive":
                        if (!data.contains("No Data")) {
                            ResponseResult incentive = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (incentive != null && !db.insertDashIncentive(incentive)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "AppDashboard_Incentive not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("AppDashboard_Incentive");
                        }

                        break;

                    case "AppDashboard_L3MOffTake_Counter":
                        if (!data.contains("No Data")) {
                            ResponseResult offtakeCounter = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (offtakeCounter != null && !db.insertDashOffTakeCounter(offtakeCounter)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "L3MOffTake_Counter not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("AppDashboard_L3MOffTake_Counter");
                        }

                        break;

                    case "AppDashboard_L3MOffTake_Nuance":
                        if (!data.contains("No Data")) {
                            ResponseResult offtakeNuance = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (offtakeNuance != null && !db.insertDashOffTakeNuance(offtakeNuance)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "L3MOffTake_Nuance not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("AppDashboard_L3MOffTake_Nuance");
                        }

                        break;

                    case "AppDashboard_L3MOffTake_SubAxe":
                        if (!data.contains("No Data")) {
                            ResponseResult offtakeSubAxe = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (offtakeSubAxe != null && !db.insertDashOffTakeSubAxe(offtakeSubAxe)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "L3MOffTake_SubAxe not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("AppDashboard_L3MOffTake_SubAxe");
                        }

                        break;

                    case "ReportDaily_TVA":
                        if (!data.contains("No Data")) {
                            ResponseResult dailyTva = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (dailyTva != null && !db.insertDailyTVA(dailyTva)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "ReportDaily_TVA not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("ReportDaily_TVA");
                        }

                        break;

                    case "Report_SalesGrowth_Counter":
                        if (!data.contains("No Data")) {
                            ResponseResult salesGrowth = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (salesGrowth != null && !db.insertReportSalesGrowthCounter(salesGrowth)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_SalesGrowth_Counter not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_SalesGrowth_Counter");
                        }

                        break;

                    case "Report_SalesGrowth_CounterDetail":
                        if (!data.contains("No Data")) {
                            ResponseResult salesGrowthSubAxe = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (salesGrowthSubAxe != null && !db.insertSalesGrowthCounterSubAxe(salesGrowthSubAxe)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_SalesGrowth_CounterDetail not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_SalesGrowth_CounterDetail");
                        }

                        break;

                    case "Report_TesterCounter":
                        if (!data.contains("No Data")) {
                            TesterCounter testerCounter = new Gson().fromJson(data, TesterCounter.class);
                            db.open();
                            if (testerCounter != null && testerCounter.getReportTesterCounter()!=null && !db.insertTesterCounter(testerCounter)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_TesterCounter not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_TesterCounter");
                        }

                        break;

                    case "Report_TesterCounterDetail":
                        if (!data.contains("No Data")) {
                            ResponseResult testerCounterDetail = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (testerCounterDetail != null && !db.insertTesterCounterDetail(testerCounterDetail)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_TesterCounterDetail not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_TesterCounterDetail");
                        }

                        break;

                    case "Report_CounterVolume":
                        if (!data.contains("No Data")) {
                            ResponseResult counterVolume = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (counterVolume != null && !db.insertCounterVolume(counterVolume)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_CounterVolume not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_CounterVolume");
                        }

                        break;

                    case "Report_CounterVolumeDetail":
                        if (!data.contains("No Data")) {
                            ResponseResult counterVolumeDetail = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (counterVolumeDetail != null && !db.insertCounterVolumeDetail(counterVolumeDetail)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_CounterVolumeDetail not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_CounterVolumeDetail");
                        }

                        break;

                    case "Report_ConterValue":
                        if (!data.contains("No Data")) {
                            ResponseResult counterValue = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (counterValue != null && !db.insertCounterValue(counterValue)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_ConterValue not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_ConterValue");
                        }

                        break;

                    case "Report_ConterValueDetail":
                        if (!data.contains("No Data")) {
                            ResponseResult counterVolumeDetail = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (counterVolumeDetail != null && !db.insertCounterValueDetail(counterVolumeDetail)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_ConterValueDetail not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_ConterValueDetail");
                        }

                        break;

                    case "Report_CounterInwardStock":
                        if (!data.contains("No Data")) {
                            ResponseResult cInwordStk = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (cInwordStk != null && !db.insertCounterInwardStock(cInwordStk)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_CounterInwardStock not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_CounterInwardStock");
                        }

                        break;

                    case "Report_CounterInwardStockDetail":
                        if (!data.contains("No Data")) {
                            ResponseResult counterInwDDetail = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (counterInwDDetail != null && !db.insertCounterInwardStockDetail(counterInwDDetail)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_CounterInwardStockDetail not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_CounterInwardStockDetail");
                        }

                        break;

                    case "Report_CounterStockLedger":
                        if (!data.contains("No Data")) {
                            ResponseResult cInwordStk = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (cInwordStk != null && !db.insertCounterStockledger(cInwordStk)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_CounterStockLedger not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_CounterStockLedger");
                        }

                        break;

                    case "Report_CounterStockLedgerDetail":
                        if (!data.contains("No Data")) {
                            ResponseResult counterInwDDetail = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (counterInwDDetail != null && !db.insertCounterStockLedgerDetail(counterInwDDetail)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_CounterStockLedgerDetail not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_CounterStockLedgerDetail");
                        }

                        break;

                    case "Report_BA_TBASale":
                        if (!data.contains("No Data")) {
                            ResponseResult baTbaSales = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (baTbaSales != null && !db.insertBaTbaSales(baTbaSales)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_BA_TBASale not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_BA_TBASale");
                        }

                        break;

                    case "Report_BA_TBAPromoSale":
                        if (!data.contains("No Data")) {
                            ResponseResult baTbaPromoSales = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (baTbaPromoSales != null && !db.insertBaTbaPromoSales(baTbaPromoSales)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Report_BA_TBAPromoSale not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Report_BA_TBAPromoSale");
                        }

                        break;

                    case "T_LeaveRequestDetail":
                        if (!data.contains("No Data")) {
                            ResponseResult leaveRequestDetail = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (leaveRequestDetail != null && !db.insertLeaveDetails(leaveRequestDetail)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "T_LeaveRequestDetail not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("T_LeaveRequestDetail");
                        }

                        break;

                    case "Master_HolidayList":
                        if (!data.contains("No Data")) {
                            ResponseResult holidayList = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (holidayList != null && !db.insertHolidays(holidayList)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "Master_HolidayList not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("Master_HolidayList");
                        }

                        break;

                        case "T_LeaveLedgerSummary":
                        if (!data.contains("No Data")) {
                            ResponseResult leaveLedger = new Gson().fromJson(data, ResponseResult.class);
                            db.open();
                            if (leaveLedger != null && !db.insertLeaveLedger(leaveLedger)) {
                                pd.dismiss();
                                AlertandMessages.showToastMsg(context, "T_LeaveLedgerSummary not saved");
                            }
                        } else {
                            db.open();
                            db.delete_table_data("T_LeaveLedgerSummary");
                        }

                        break;

                    case "Mapping_AppRestrictedKPI":
                        if (!data.contains("No Data")) {
                            MasterBAProfileGetterSetter  mappingAppRestrictedKPIGetterSetter = new Gson().fromJson(data, MasterBAProfileGetterSetter.class);
                            db.open();
                            if (mappingAppRestrictedKPIGetterSetter != null && !db.insertMappingAppRestrictedKPI(mappingAppRestrictedKPIGetterSetter)) {
                                AlertandMessages.showToastMsg(context, "Mapping_AppRestrictedKPI data not saved");
                                pd.dismiss();
                            }
                        } else {
                            throw new java.lang.Exception();
                        }
                        break;


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

            return null;
        }
    }

    @SuppressLint("StaticFieldLeak")
    private class DownloadImageTask extends AsyncTask<String, String, String> {
        Context context;
        MasterBAProfileGetterSetter masterPromoOffer;
        JCPGetterSetter baListObject;

        DownloadImageTask(Context context, MasterBAProfileGetterSetter masterPromoOffer, JCPGetterSetter baListObject) {
            this.masterPromoOffer = masterPromoOffer;
            this.context = context;
            this.baListObject = baListObject;
        }

        @Override
        protected String doInBackground(String... strings) {
            try {
                //insert stock all dats
                if (masterPromoOffer != null) {
                    downloadImages(masterPromoOffer);
                }

                if (baListObject != null) {
                    downloadImagesbaprofile(baListObject);
                }

                return CommonString.KEY_SUCCESS;
            } catch (IOException ex) {
                return CommonString.KEY_FAILURE;
            } catch (WindowManager.BadTokenException e) {
                //use a log message
                return CommonString.KEY_FAILURE;
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            pd.dismiss();
            db.open();
            if (db.isTStockt(date, counterId) && db.isTStockSummeryCheckNoData(date, counterId)) {
                int first_tStockSummery = preferences.getInt(CommonString.KEY_FIRST_DOWNLOAD_TsTOCK + date, 0);
                if (first_tStockSummery != 0) {
                    db.open();
                    if (db.isTStockCorrectedinsert(date, counterId)) {
                        editor = preferences.edit();
                        editor.putInt(CommonString.KEY_FIRST_DOWNLOAD_TsTOCK + date, 0);
                        editor.putInt(CommonString.KEY_INCORRECT_TSTOCK_SUMMERY + date, 1);
                        editor.apply();
                    } else {
                        db.open();
                        db.delete_table_data("T_StockSummary");
                        editor = preferences.edit();
                        editor.putInt(CommonString.KEY_INCORRECT_TSTOCK_SUMMERY + date, 2);
                        editor.apply();
                    }
                }
            } else {
                editor = preferences.edit();
                editor.putInt(CommonString.KEY_FIRST_DOWNLOAD_TsTOCK + date, 0);
                editor.putInt(CommonString.KEY_INCORRECT_TSTOCK_SUMMERY + date, 0);
                editor.apply();
            }

            int incorrect_tStockSummery = preferences.getInt(CommonString.KEY_INCORRECT_TSTOCK_SUMMERY + date, 0);
            if (incorrect_tStockSummery != 0) {
                if (incorrect_tStockSummery == 1) {
                    AlertandMessages.showAlert((Activity) context, context.getString(R.string.datasyncedcompeletely), true);
                } else if (incorrect_tStockSummery == 2) {
                    AlertandMessages.showAlertfordatanotSyncedcompeletetly((Activity) context, context.getString(R.string.datanotsyncedcompletely), true);
                } else {
                    AlertandMessages.showAlert((Activity) context, context.getString(R.string.datasyncedcompeletely), true);
                }
            } else {
                AlertandMessages.showAlert((Activity) context, context.getString(R.string.datasyncedcompeletely), true);
            }
        }
    }


    void downloadImages(MasterBAProfileGetterSetter promotion_object) throws IOException {
        List<MasterPromoOffer> data = promotion_object.getMasterPromoOffers();
        try {
            File folder = new File(CommonString.getPromosFolder(context));
            if (!folder.isDirectory()) {
                folder.mkdir();
            }
            /////////Download promotion banner for mobile
            if (!data.isEmpty()) {
                for (int i = 0; i < data.size(); i++) {
                    if (data.get(i).getPromoOfferMobile() != null && !data.get(i).getPromoOfferMobile().isEmpty()
                            && data.get(i).getPromoPath() != null && !data.get(i).getPromoPath().isEmpty()) {
                        downloadFile(data.get(i).getPromoPath(), data.get(i).getPromoOfferMobile(), folder);
                    }
                }
            }

            /////////Download promotion banner for Tablet
            List<MasterPromoOffer> datafor_tab = promotion_object.getMasterPromoOffers();
            if (!datafor_tab.isEmpty()) {
                for (int i = 0; i < datafor_tab.size(); i++) {
                    if (datafor_tab.get(i).getPromoOfferTab() != null && !datafor_tab.get(i).getPromoOfferTab().isEmpty()
                            && datafor_tab.get(i).getPromoPath() != null && !datafor_tab.get(i).getPromoPath().isEmpty()) {
                        downloadFile(datafor_tab.get(i).getPromoPath(), datafor_tab.get(i).getPromoOfferTab(), folder);
                    }
                }
            }

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


    public void downloadFile(String fileUrl, String directory, File folder_path) {
        try {
            URL url = new URL(fileUrl + directory);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.getResponseCode();
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 200) {
                int length = urlConnection.getContentLength();
                String size = new DecimalFormat("##.##").format((double) ((double) length / 1024)) + " KB";
                if (!new File(folder_path.getPath() + directory).exists() && !size.equalsIgnoreCase("0 KB")) {
                    File outputFile = new File(folder_path, directory);
                    FileOutputStream fos = new FileOutputStream(outputFile);
                    InputStream is1 = (InputStream) urlConnection.getInputStream();
                    int bytes = 0;
                    byte[] buffer = new byte[1024];
                    int len1 = 0;

                    while ((len1 = is1.read(buffer)) != -1) {
                        bytes = (bytes + len1);
                        fos.write(buffer, 0, len1);
                    }

                    fos.close();
                    is1.close();
                }
            }
        } catch (ProtocolException e) {
            e.fillInStackTrace();
        } catch (IOException e) {
            FirebaseCrashlytics.getInstance().recordException(e);
            e.fillInStackTrace();
        }
    }

    void downloadImagesbaprofile(JCPGetterSetter baprofileObject) throws IOException {
        List<BaListGetterSetter> data = baprofileObject.getBAList();
        try {
            File folder = new File(CommonString.getProfileFolder(context));
            if (!folder.isDirectory()) {
                folder.mkdir();
            }
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).getProfilePic() != null && !data.get(i).getProfilePic().isEmpty() && data.get(i).getProfilePath() != null && !data.get(i).getProfilePath().isEmpty()) {
                    downloadFile(data.get(i).getProfilePath(), data.get(i).getProfilePic(), folder);
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }

    }

    public void downloadDataUniversalBa(final ArrayList<String> jsonStringList, final ArrayList<String> KeyNames, int downloadindex, int type) {
        status = 0;
        isvalid = false;
        final String[] data_global = {""};
        String jsonString = "", KeyName = "";
        int jsonIndex = 0;

        if (!jsonStringList.isEmpty()) {
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            jsonString = jsonStringList.get(downloadindex);
            KeyName = KeyNames.get(downloadindex);
            jsonIndex = downloadindex;

            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString);
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<String> call = api.getDownloadAll(jsonData);
            final int[] finalJsonIndex = {jsonIndex};
            final String finalKeyName = KeyName;

            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                    String responseBody = response.body();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body();
                            assert data != null;
                            if (data.isEmpty()) {
                                data_global[0] = "";
                            } else {
                                data_global[0] = data;
                                if (finalKeyName.equalsIgnoreCase("Table_Structure")) {
                                    editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]);
                                    editor.apply();
                                    tableStructureObj = new Gson().fromJson(data, TableStructureGetterSetter.class);
                                    String isAllTableCreated = createTable(tableStructureObj);

                                    if (isAllTableCreated != CommonString.KEY_SUCCESS) {
                                        AlertandMessages.showAlert((Activity) context, isAllTableCreated + " not created", true);
                                    }
                                } else {
                                    editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]);
                                    editor.apply();
                                    switch (finalKeyName) {
                                        case "BA_List":
                                            if (!data.contains("No Data")) {
                                                baListObject = new Gson().fromJson(data, JCPGetterSetter.class);
                                                db.open();
                                                if (baListObject != null && !db.insertBalistData(baListObject)) {
                                                    AlertandMessages.showSnackbarMsg(context, "Ba List data not saved");
                                                }
                                            } else {
                                                throw new java.lang.Exception();
                                            }
                                            break;

                                        case "Mapping_JourneyPlan":
                                            if (!data.contains("No Data")) {
                                                jcpObject = new Gson().fromJson(data, JCPGetterSetter.class);
                                                db.open();
                                                if (jcpObject != null && !db.insertJCPData(jcpObject)) {
                                                    AlertandMessages.showSnackbarMsg(context, "JCP data not saved");
                                                }
                                            }

                                            break;
                                        case "ServerTime":
                                            if (!data.contains("No Data")) {
                                                serverTimeObj = new Gson().fromJson(data, ServerTimeGetterSetter.class);
                                                if (serverTimeObj != null) {
                                                    db.open();
                                                    db.insertServerTimeData(serverTimeObj);
                                                    try {
                                                        String tymStr = calculateTotalDuration(CommonFunctions.setTimeFormat(serverTimeObj.getServerTime().get(0).getServerTime()));
                                                        String s[] = tymStr.split(":");
                                                        int t = Integer.parseInt(s[0]);
                                                        int t2 = Integer.parseInt(s[1]);
                                                        if (t > 0) {
                                                            CommonFunctions.show_incurrect_device_tym(context, serverTimeObj.getServerTime().get(0).getServerTime());
                                                        } else if (t2 > 10) {
                                                            CommonFunctions.show_incurrect_device_tym(context, serverTimeObj.getServerTime().get(0).getServerTime());
                                                        }
                                                    } catch (NumberFormatException e) {
                                                        e.fillInStackTrace();
                                                    }
                                                }
                                            }

                                            break;

                                    }
                                }
                            }

                            finalJsonIndex[0]++;
                            if (finalJsonIndex[0] != KeyNames.size()) {
                                downloadDataUniversalBa(jsonStringList, KeyNames, finalJsonIndex[0], CommonString.DOWNLOAD_ALL_SERVICE);
                            }

                        } catch (Exception e) {
                            e.fillInStackTrace();
                            editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]);
                            editor.apply();
                        }
                    } else {
                        editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]);
                        editor.apply();
                    }
                }

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                    isvalid = true;
                }
            });
        }
    }


    private String calculateTotalDuration(String serverTym) {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss");
        int days = 0, hours = 0, min = 0;
        String str_hours = "";
        try {
            Date date1 = simpleDateFormat.parse(serverTym);
            Date date2 = simpleDateFormat.parse(getTime());
            assert date2 != null;
            assert date1 != null;
            long difference = date2.getTime() - date1.getTime();
            days = (int) (difference / (1000 * 60 * 60 * 24));
            hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
            min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60);
            hours = (hours < 0 ? -hours : hours);
            Log.i("======= Hours", " :: " + hours);
        } catch (ParseException e) {
            e.fillInStackTrace();
        }

        if (hours != 0 && hours < 10) {
            str_hours = "0" + hours;
        } else {
            str_hours = String.valueOf(hours);
        }

        return str_hours + ":" + min;
    }

    private String getTime() {
        Calendar currnetDateTime = Calendar.getInstance();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss");
        return df.format(currnetDateTime.getTime());
    }

}
