package com.cpm.lorealbaMabeline.download;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.widget.TextView;
import android.widget.VideoView;

import com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;
import com.cpm.lorealbaMabeline.retrofit.DownloadAllDatawithRetro;

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

import java.util.ArrayList;


public class DownloadActivity extends AppCompatActivity {
    Lorealba_Database db;
    String userId, date, counter_id = "";
    private SharedPreferences preferences = null;
    SharedPreferences.Editor editor;
    Toolbar toolbar;
    Context context;
    int downloadindex = 0, tagfor_downloadalldata = 0;
    VideoView vedio_view, vedio_view_2;
    ProgressDialog pd;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        context = this;
        db = new Lorealba_Database(context);
        preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();

        userId = preferences.getString(CommonString.KEY_USERNAME, "");
        date = preferences.getString(CommonString.KEY_DATE, "");
        counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        downloadindex = preferences.getInt(CommonString.KEY_DOWNLOAD_INDEX, 0);
        tagfor_downloadalldata = getIntent().getIntExtra(CommonString.TAG_FROM, 0);
        vedio_view = (VideoView) findViewById(R.id.vedio_view);
        vedio_view_2 = (VideoView) findViewById(R.id.vedio_view_2);
        String path = "android.resource://" + getPackageName() + "/" + R.raw.giffy;
        vedio_view.setVideoURI(Uri.parse(path));
        vedio_view.start();
        vedio_view_2.setVideoURI(Uri.parse(path));
        vedio_view_2.start();
        vedio_view.resume();
        vedio_view_2.resume();
        setTitle("Downloading Data - " + date);
        String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, "");
        TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code);
        txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id);
        UploadDataTask();
    }

    public void UploadDataTask() {
        try {
            ArrayList<String> keysList = new ArrayList<>();
            ArrayList<String> jsonList = new ArrayList<>();
            ArrayList<String> KeyNames = new ArrayList<>();
            keysList.add("Table_Structure");
            if (tagfor_downloadalldata == 1) {
                keysList.add("StockSummary_Check");
                keysList.add("T_StockSummary");
                editor = preferences.edit();
                editor.putInt(CommonString.KEY_FIRST_DOWNLOAD_TsTOCK + date, 1);
                editor.commit();
            } else {
                keysList.add("Mapping_JourneyPlan");
                keysList.add("BA_List");
                keysList.add("ServerTime");
                keysList.add("Mapping_CounterGroup_Brand");
                keysList.add("Mapping_Visibility");
                keysList.add("Master_Posm");
                keysList.add("T_CounterInvoice");
                keysList.add("Master_NonVisibility");
                keysList.add("Master_SkinType");
                keysList.add("Master_AgeLimit");
                keysList.add("Master_Profile");
                keysList.add("Master_ProfileQuestion");
                keysList.add("Master_SkinType");
                keysList.add("Master_AgeLimit");
                keysList.add("Master_NonStockReason");
                keysList.add("Master_ReturnReason");
                keysList.add("Master_TermsCondition");
                keysList.add("T_LeaveRequest");
                //keysList.add("T_LeaveLedger");
                keysList.add("Master_Break");
                keysList.add("Master_InvoiceType");
                /////Checking T_StockSummery and StockSummeryCheck size is not from current date
                db.open();
                if (!db.isTStockSummaryFilled(date)) {
                    keysList.add("StockSummary_Check");
                    keysList.add("T_StockSummary");
                    editor = preferences.edit();
                    editor.putInt(CommonString.KEY_FIRST_DOWNLOAD_TsTOCK + date, 1);
                    editor.commit();
                }

                ///download_report by JP
                keysList.add("Report_SalesValue");
                keysList.add("Report_Sales_Detail");
                keysList.add("Report_AvgTransactionPerDay");
                keysList.add("Report_AvgUnitsPerBill");
                keysList.add("Report_AvgBillValue");
                keysList.add("Report_AvgLinPerBill");
                keysList.add("Report_SellingPrice");
                keysList.add("Report_Top10Volume");
                keysList.add("Report_Top10Value");
                keysList.add("Master_BAProfile");
                keysList.add("Master_PromoOffers");
                keysList.add("Report_AttendanceDetail");
                keysList.add("Report_AttendanceSummary");
                keysList.add("Report_InwardStockSummary");
                keysList.add("Report_BA_Availability");
                keysList.add("Master_Looks");
                keysList.add("ME_MEAuditQuestion");
                //promotion related
                keysList.add("Master_Promotion");
                keysList.add("Master_PromotionSetEntityItem");
                keysList.add("Master_PromotionGetEntityItem");
                keysList.add("Master_PromotionSetProductGroup");
                keysList.add("Master_PromotionGetProductGroup");
                keysList.add("Master_Survey");
                keysList.add("Master_LeaveType");
                keysList.add("Damage_ReturnToDistributor");
                keysList.add("Master_Survey_UploadStatus");
                keysList.add("ME_MEAuditQuestion_UploadStatus");
                keysList.add("Master_PromotionSetProductCatalog");
                keysList.add("Master_PromotionGetProductCatalog");
                keysList.add("Report_ProductGroupWiseSalesValue");
                keysList.add("Report_SalesDateWise");
                keysList.add("Damage_PreviousPending");
                keysList.add("SkinGeniusUrl");
                keysList.add("Report_SalesL3MValue");
                keysList.add("Master_PromotionSetExclusionList");
                keysList.add("Master_PromotionGetExclusionList");
                keysList.add("Master_SourcesOfSales");
                keysList.add("Report_DamageStockHistory");
                keysList.add("Master_CompetitonBrandWiseNuance");
                keysList.add("Master_CompetitionOfferSet");
                keysList.add("Master_CompetitionOfferGet");
                keysList.add("Master_CompetitionPromoType");
                keysList.add("Master_CompetitionProductType");
                ////////
                keysList.add("Master_CompetitionOffer");
                keysList.add("Master_CompetitionOfferSaleRange");
                keysList.add("Master_RetailExcellence_Item");
                keysList.add("D2D_ARS");
                ///new report for me
                keysList.add("Report_Sales_DetailME");
                keysList.add("Report_SalesDateWiseME");
                keysList.add("Report_SalesL3MValueME");
                keysList.add("Report_MTD_WorkingCounterME");
                keysList.add("AppDashboard_TVA");
                keysList.add("AppDashboard_TVADrillDown");
                keysList.add("AppDashboard_LeaderBoard");
                keysList.add("AppDashboard_Incentive");
                keysList.add("ReportDaily_TVA");
                keysList.add("Report_SalesGrowth_Counter");
                keysList.add("Report_SalesGrowth_CounterDetail");
                keysList.add("Report_TesterCounterDetail");
                keysList.add("Report_TesterCounter");
                keysList.add("Report_CounterVolume");
                keysList.add("Report_CounterVolumeDetail");
                keysList.add("Report_ConterValue");
                keysList.add("Report_ConterValueDetail");
                keysList.add("Report_CounterInwardStock");
                keysList.add("Report_CounterInwardStockDetail");
                keysList.add("Report_CounterStockLedger");
                keysList.add("Report_CounterStockLedgerDetail");
                keysList.add("Report_BA_TBAPromoSale");
                keysList.add("Report_BA_TBASale");
                keysList.add("T_LeaveRequestDetail");
                keysList.add("Master_HolidayList");
                keysList.add("T_LeaveLedgerSummary");
                keysList.add("Mapping_AppRestrictedKPI");
                keysList.add("Master_CheckoutQuestion");
                keysList.add("Product_Master");
            }

            if (!keysList.isEmpty()) {
                for (int i = 0; i < keysList.size(); i++) {
                    JSONObject jsonObject1 = getJsonObject(keysList, i);
                    jsonList.add(jsonObject1.toString());
                    KeyNames.add(keysList.get(i));
                }

                if (!jsonList.isEmpty()) {
                    pd = new ProgressDialog(context);
                    pd.setCancelable(false);
                    pd.setMessage("Downloading Data" + "(" + "/" + ")");
                    pd.show();
                    DownloadAllDatawithRetro downloadData = new DownloadAllDatawithRetro(context, db, pd, CommonString.TAG_FROM_CURRENT);
                    downloadData.listSize = jsonList.size();
                    downloadData.downloadDataUniversalWithoutWait(jsonList, KeyNames, downloadindex, CommonString.DOWNLOAD_ALL_SERVICE);
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    private @NonNull JSONObject getJsonObject(ArrayList<String> keysList, int i) throws JSONException {
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("Downloadtype", keysList.get(i));
        jsonObject1.put("Username", userId);
        jsonObject1.put("Param1", counter_id);
        jsonObject1.put("Param2", keysList.get(i).equals("Report_TesterCounterDetail")
                || keysList.get(i).equals("Report_CounterVolumeDetail")
                || keysList.get(i).equals("Report_ConterValueDetail")
                || keysList.get(i).equals("Report_CounterInwardStockDetail")
                || keysList.get(i).equals("Report_CounterStockLedgerDetail")
                || keysList.get(i).equals("Report_SalesGrowth_CounterDetail") ? "AxeName" : "");
        return jsonObject1;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (pd != null && pd.isShowing()) {
            pd.cancel();
        }
    }
}
