package in.techware.carrefour.activity;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.HapticFeedbackConstants;
import android.view.View;
import android.widget.Button;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import in.techware.carrefour.R;
import in.techware.carrefour.config.Config;
import in.techware.carrefour.dbUtils.repositories.FacingRepository;
import in.techware.carrefour.dbUtils.repositories.InternalSalesCorrectionRepository;
import in.techware.carrefour.dbUtils.repositories.InternalSalesRepository;
import in.techware.carrefour.dbUtils.repositories.ItemListRepository;
import in.techware.carrefour.dbUtils.repositories.LabelSurveyRepository;
import in.techware.carrefour.dbUtils.repositories.MinStockRepository;
import in.techware.carrefour.dbUtils.repositories.OutOfStockRepository;
import in.techware.carrefour.dbUtils.repositories.PrintLabelRepository;
import in.techware.carrefour.dbUtils.repositories.PromotionRepository;
import in.techware.carrefour.dbUtils.repositories.StockTakeRepository;
import in.techware.carrefour.dbUtils.repositories.TransformQuantityRepository;
import in.techware.carrefour.dbUtils.repositories.WasteRepository;
import in.techware.carrefour.dialogs.ConfirmationDialog;
import in.techware.carrefour.dialogs.PopupMessage;
import in.techware.carrefour.model.FacingBean;
import in.techware.carrefour.model.InternalSalesBean;
import in.techware.carrefour.model.InternalSalesCorrectionBean;
import in.techware.carrefour.model.ItemListBean;
import in.techware.carrefour.model.LabelSurveyBean;
import in.techware.carrefour.model.MenuBean;
import in.techware.carrefour.model.MinStockBean;
import in.techware.carrefour.model.OutOfStockBean;
import in.techware.carrefour.model.PrintLabelBean;
import in.techware.carrefour.model.PromotionBean;
import in.techware.carrefour.model.StockTakeBean;
import in.techware.carrefour.model.TransformQuantityBean;
import in.techware.carrefour.model.WasteBean;
import in.techware.carrefour.net.WSTasks.FTPUploadTask;
import in.techware.carrefour.util.AppConstants;
import in.techware.carrefour.util.BarcodeUtil;
import in.techware.carrefour.util.FileTransferUtil;
import in.techware.carrefour.util.menuUtils.HomeMenuUtil;
import in.techware.carrefour.util.menuUtils.ITMenuUtil;
import in.techware.carrefour.viewModels.FileTransferViewModel;

import static in.techware.carrefour.util.FileOp.SENT_FILES;
import static in.techware.carrefour.util.FileOp.SEPARATOR;

public class FileTransferActivity extends BaseAppCompatNoDrawerActivity {

    private static final int REQ_PIT_NUMBER = 1;
    private static final String TAG = "FileTransferA";
    private MenuBean selectedMenuBean;
    private MenuBean selectedSubMenuBean;
    private int labelType = 0;
    private String fileName;
    private Button btnSendData;
    private Button btnContinue;
    private Button btnMainMenu;
    private FileTransferViewModel viewModel;
    private WasteRepository.WasteRepositoryListener wasteRepositoryListener;
    private WasteRepository wasteRepository;
    private LabelSurveyRepository labelSurveyRepository;
    private LabelSurveyRepository.LabelSurveyRepositoryListener labelSurveyRepositoryListener;
    private StockTakeRepository stockTakeRepository;
    private StockTakeRepository.StockTakeRepositoryListener stockTakeRepositoryListener;
    private MinStockRepository minStockRepository;
    private MinStockRepository.MinStockRepositoryListener minStockRepositoryListener;
    private FacingRepository facingRepository;
    private FacingRepository.FacingRepositoryListener facingRepositoryListener;
    private PromotionRepository promotionRepository;
    private PromotionRepository.PromotionRepositoryListener promotionRepositoryListener;
    private OutOfStockRepository outOfStockRepository;
    private OutOfStockRepository.OutOfStockRepositoryListener outOfStockRepositoryListener;
    private TransformQuantityRepository transformQuantityRepository;
    private TransformQuantityRepository.TransformQuantityRepositoryListener transformQuantityRepositoryListener;
    private ItemListRepository itemListRepository;
    private ItemListRepository.ItemListRepositoryListener itemListRepositoryListener;
    private InternalSalesRepository internalSalesRepository;
    private InternalSalesRepository.InternalSalesRepositoryListener internalSalesRepositoryListener;
    private InternalSalesCorrectionRepository internalSalesCorrectionRepository;
    private InternalSalesCorrectionRepository.InternalSalesCorrectionRepositoryListener internalSalesCorrectionRepositoryListener;
    private PrintLabelRepository printLabelRepository;
    private PrintLabelRepository.PrintLabelRepositoryListener printLabelRepositoryListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_transfer);
        if (getIntent() != null && getIntent().hasExtra("menuBean")) {
            selectedMenuBean = (MenuBean) getIntent().getSerializableExtra("menuBean");
        }
        if (getIntent() != null && getIntent().hasExtra("subMenuBean")) {
            selectedSubMenuBean = (MenuBean) getIntent().getSerializableExtra("subMenuBean");
        }
        if (getIntent() != null && getIntent().hasExtra("labelType")) {
            labelType = getIntent().getIntExtra("labelType", 0);
        }

        viewModel = (FileTransferViewModel) ViewModelProviders.of(this).get(FileTransferViewModel.class);


        initViews();
        setRepositories();

        if (getSupportActionBar() != null) {
            setTitle(R.string.title_file_transfer, R.color.white);
            getSupportActionBar().setTitle("");
            getSupportActionBar().setDisplayShowTitleEnabled(true);
        }


    }

    private void initViews() {

        fileName = AppConstants.getFileName(selectedMenuBean, selectedSubMenuBean, labelType);

        btnSendData = findViewById(R.id.btn_file_transfer_send_data);
        btnContinue = findViewById(R.id.btn_file_transfer_continue);
        btnMainMenu = findViewById(R.id.btn_file_transfer_main_menu);

        btnSendData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onFileTransferSendDataClick(v);
            }
        });
        btnContinue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onFileTransferContinueClick(v);
            }
        });
        btnMainMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onFileTransferMainMenuClick(v);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQ_PIT_NUMBER && resultCode == RESULT_OK) {
            viewModel.setPitNumber(data.getStringExtra("pitNumber"));
            switch (selectedMenuBean.getCode()) {
                case HomeMenuUtil.CODE_IT:
                    switch (selectedSubMenuBean.getCode()) {
                        case ITMenuUtil.CODE_STOCK_TAKE:
                            stockTakeRepository.getAllUnsentStockTakes(stockTakeRepositoryListener);
                            break;

                        case ITMenuUtil.CODE_PRINT_LABELS:
                            break;

                        case ITMenuUtil.CODE_MIN_STOCK:
                            break;

                        case ITMenuUtil.CODE_FACING:
                            break;

                        case ITMenuUtil.CODE_PROMOTION:
                            break;

                        case ITMenuUtil.CODE_OUT_OF_STOCK:
                            break;

                        case ITMenuUtil.CODE_TRANSFORM_QUANTITY:
                            break;

                        case ITMenuUtil.CODE_ITEM_LIST:
                            break;

                        case ITMenuUtil.CODE_INTERNAL_SALES:
                            break;
                        case ITMenuUtil.CODE_INTERNAL_SALES_CORRECT:
                            break;
                        case ITMenuUtil.CODE_EXIT:
                            break;
                    }
                    break;
                case HomeMenuUtil.CODE_RECEIVE:
                    break;
                case HomeMenuUtil.CODE_ELIE:
                    break;
                case HomeMenuUtil.CODE_ORDERS:
                    break;
                case HomeMenuUtil.CODE_INFO:
                    break;
                case HomeMenuUtil.CODE_MERCHAND:
                    break;
                case HomeMenuUtil.CODE_FOOD_BANK:
                    break;
            }


        }
    }

    private void setRepositories() {
        switch (selectedMenuBean.getCode()) {
            case HomeMenuUtil.CODE_IT:
                switch (selectedSubMenuBean.getCode()) {
                    case ITMenuUtil.CODE_WASTE:
                        setWasteRepository();
                        break;
                    case ITMenuUtil.CODE_LABEL_SURVEY:
                        setLabelSurveyRepository();
                        break;
                    case ITMenuUtil.CODE_STOCK_TAKE:
                        setStockTakeRepository();
                        break;
                    case ITMenuUtil.CODE_PRINT_LABELS:
                        setPrintLabelRepository();
                        break;
                    case ITMenuUtil.CODE_MIN_STOCK:
                        setMinStockRepository();
                        break;
                    case ITMenuUtil.CODE_FACING:
                        setFacingRepository();
                        break;
                    case ITMenuUtil.CODE_PROMOTION:
                        setPromotionRepository();
                        break;
                    case ITMenuUtil.CODE_OUT_OF_STOCK:
                        setOutOfStockRepository();
                        break;
                    case ITMenuUtil.CODE_TRANSFORM_QUANTITY:
                        setTransformQuantityRepository();
                        break;
                    case ITMenuUtil.CODE_ITEM_LIST:
                        setItemListRepository();
                        break;
                    case ITMenuUtil.CODE_INTERNAL_SALES:
                        setInternalSalesRepository();
                        break;
                    case ITMenuUtil.CODE_INTERNAL_SALES_CORRECT:
                        setInternalSalesCorrectionRepository();
                        break;
                    case ITMenuUtil.CODE_EXIT:
                        break;
                }
                break;
            case HomeMenuUtil.CODE_RECEIVE:
                break;
            case HomeMenuUtil.CODE_ELIE:
                break;
            case HomeMenuUtil.CODE_ORDERS:
                break;
            case HomeMenuUtil.CODE_INFO:
                break;
            case HomeMenuUtil.CODE_MERCHAND:
                break;
            case HomeMenuUtil.CODE_FOOD_BANK:
                break;
        }
    }

    private void setWasteRepository() {
        wasteRepository = new WasteRepository();
        wasteRepositoryListener = new WasteRepository.WasteRepositoryListener() {
            @Override
            public void onAddCompleted(WasteBean wasteBean) {

            }

            @Override
            public void onAllListLoaded(ArrayList<WasteBean> wasteList) {

            }

            @Override
            public void onAllSentListLoaded(ArrayList<WasteBean> wasteList) {

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<WasteBean> wasteList) {
                if (wasteList != null && !wasteList.isEmpty()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    ArrayList<WasteBean> list = FileTransferUtil.getUniqueWasteList(wasteList);
                    for (WasteBean bean : list) {
                        if (wasteList.indexOf(bean) != 0) {
                            stringBuilder.append("\n");
                        }
                        stringBuilder.append("DM")
                                .append(BarcodeUtil.getFormattedBarcode(bean.getBarcode()))
                                .append(AppConstants.SPACE)
                                .append(BarcodeUtil.getFormattedQuantity(bean.getQuantity(), 8, true))
                                .append(bean.getOriginTypeCode());
                    }

                    viewModel.setWasteList(wasteList);
                    fop.writeFile(stringBuilder.toString(), fileName);
                    uploadFile(fileName, "");

                }
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {
                for (WasteBean bean : viewModel.getWasteList()) {
                    bean.setSendStatus(1);
                    wasteRepository.updateWaste(bean, wasteRepositoryListener);
                }
                finishTask(AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED);
            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onDeleteCompleted(WasteBean wasteBean) {

            }

            @Override
            public void onFailed() {

            }

            @Override
            public void onUpdateCompleted(WasteBean wasteBean) {

            }

            @Override
            public void onWasteBeanLoaded(WasteBean wasteBean) {

            }
        };
    }

    private void setLabelSurveyRepository() {
        labelSurveyRepository = LabelSurveyRepository.getInstance();
        labelSurveyRepositoryListener = new LabelSurveyRepository.LabelSurveyRepositoryListener() {
            @Override
            public void onAddCompleted(LabelSurveyBean labelSurveyBean) {

            }

            @Override
            public void onAllListLoaded(ArrayList<LabelSurveyBean> labelSurveyList) {

            }

            @Override
            public void onAllSentListLoaded(ArrayList<LabelSurveyBean> labelSurveyList) {

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<LabelSurveyBean> labelSurveyList) {
                if (labelSurveyList != null && !labelSurveyList.isEmpty()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (LabelSurveyBean bean : labelSurveyList) {
                        if (labelSurveyList.indexOf(bean) != 0) {
                            stringBuilder.append("\n");
                        }
                        stringBuilder
                                .append(BarcodeUtil.getFormattedBarcode(bean.getBarcode()))
                                .append(BarcodeUtil.getFormattedPrice(bean.getPrice()))
                                .append(Config.getInstance().getAppSettingsBean().getScanFlag());
                    }

                    viewModel.setLabelSurveyList(labelSurveyList);
                    fop.writeFile(stringBuilder.toString(), fileName);
                    uploadFile(fileName, "");

                }
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {
                for (LabelSurveyBean bean : viewModel.getLabelSurveyList()) {
                    bean.setSendStatus(1);
                    labelSurveyRepository.updateLabelSurvey(bean, labelSurveyRepositoryListener);
                }
                finishTask(AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED);
            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onDeleteCompleted(LabelSurveyBean labelSurveyBean) {

            }

            @Override
            public void onFailed() {

            }

            @Override
            public void onLabelSurveyBeanLoaded(LabelSurveyBean labelSurveyBean) {

            }

            @Override
            public void onUpdateCompleted(LabelSurveyBean labelSurveyBean) {

            }
        };
    }

    private void setStockTakeRepository() {
        stockTakeRepository = StockTakeRepository.getInstance();
        stockTakeRepositoryListener = new StockTakeRepository.StockTakeRepositoryListener() {
            @Override
            public void onAddCompleted(StockTakeBean stockTakeBean) {

            }

            @Override
            public void onAllListLoaded(ArrayList<StockTakeBean> stockTakeList) {

            }

            @Override
            public void onAllSentListLoaded(ArrayList<StockTakeBean> stockTakeList) {

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<StockTakeBean> stockTakeList) {
                if (stockTakeList != null && !stockTakeList.isEmpty()) {
                    ArrayList<StockTakeBean> list = FileTransferUtil.getUniqueStockTakeList(stockTakeList);
                    StringBuilder stringBuilder = new StringBuilder();
                    for (StockTakeBean bean : list) {
                        if (stockTakeList.indexOf(bean) != 0) {
                            stringBuilder.append("\n");
                        }
                        stringBuilder.append("IG")
                                .append(BarcodeUtil.getFormattedBarcode(bean.getBarcode()))
                                .append(BarcodeUtil.getFormattedQuantity(bean.getQuantity(), 8, true))
                                .append(bean.getZoneType())
                                .append(Config.getInstance().getAppSettingsBean().getScanFlag());
                    }

                    viewModel.setStockTakeList(stockTakeList);
                    fop.writeFile(stringBuilder.toString(), fileName + viewModel.getPitNumber());
                    uploadFile(fileName + viewModel.getPitNumber(), "");

                }
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {
                for (StockTakeBean bean : viewModel.getStockTakeList()) {
                    bean.setSendStatus(1);
                    stockTakeRepository.updateStockTake(bean, stockTakeRepositoryListener);
                }
                finishTask(AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED);
            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onDeleteCompleted(StockTakeBean stockTakeBean) {

            }

            @Override
            public void onFailed() {

            }

            @Override
            public void onStockTakeBeanLoaded(StockTakeBean stockTakeBean) {

            }

            @Override
            public void onUpdateCompleted(StockTakeBean stockTakeBean) {

            }
        };
    }

    private void setMinStockRepository() {
        minStockRepository = MinStockRepository.getInstance();
        minStockRepositoryListener = new MinStockRepository.MinStockRepositoryListener() {
            @Override
            public void onAddCompleted(MinStockBean minStockBean) {

            }

            @Override
            public void onAllListLoaded(ArrayList<MinStockBean> minStockList) {

            }

            @Override
            public void onAllSentListLoaded(ArrayList<MinStockBean> minStockList) {

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<MinStockBean> minStockList) {
                if (minStockList != null && !minStockList.isEmpty()) {
                    ArrayList<MinStockBean> list = FileTransferUtil.getUniqueMinStockList(minStockList);
                    StringBuilder stringBuilder = new StringBuilder();
                    for (MinStockBean bean : list) {
                        if (minStockList.indexOf(bean) != 0) {
                            stringBuilder.append("\n");
                        }
                        stringBuilder.append("SM")
                                .append(BarcodeUtil.getFormattedBarcode(bean.getBarcode()))
                                .append(BarcodeUtil.getFormattedQuantity(bean.getQuantity(), 8, true));
                    }

                    viewModel.setMinStockList(minStockList);
                    fop.writeFile(stringBuilder.toString(), fileName);
                    uploadFile(fileName, "");

                }
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {
                for (MinStockBean bean : viewModel.getMinStockList()) {
                    bean.setSendStatus(1);
                    minStockRepository.updateMinStock(bean, minStockRepositoryListener);
                }
                finishTask(AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED);
            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onDeleteCompleted(MinStockBean minStockBean) {

            }

            @Override
            public void onFailed() {

            }

            @Override
            public void onMinStockBeanLoaded(MinStockBean minStockBean) {

            }

            @Override
            public void onUpdateCompleted(MinStockBean minStockBean) {

            }
        };
    }

    private void setFacingRepository() {
        facingRepository = FacingRepository.getInstance();
        facingRepositoryListener = new FacingRepository.FacingRepositoryListener() {
            @Override
            public void onAddCompleted(FacingBean facingBean) {

            }

            @Override
            public void onAllListLoaded(ArrayList<FacingBean> facingList) {

            }

            @Override
            public void onAllSentListLoaded(ArrayList<FacingBean> facingList) {

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<FacingBean> facingList) {
                if (facingList != null && !facingList.isEmpty()) {
                    ArrayList<FacingBean> list = FileTransferUtil.getUniqueFacingList(facingList);
                    StringBuilder stringBuilder = new StringBuilder();
                    StringBuilder stringBuilderLabelMake = new StringBuilder();
                    for (FacingBean bean : list) {
                        if (facingList.indexOf(bean) != 0) {
                            stringBuilder.append("\n");
                            stringBuilderLabelMake.append("\n");
                        }
                        stringBuilder.append("FA")
                                .append(BarcodeUtil.getFormattedBarcode(bean.getBarcode()))
                                .append(BarcodeUtil.getFormattedQuantity(bean.getQuantity(), 8, true));
                        stringBuilderLabelMake.append("ET")
                                .append(BarcodeUtil.getFormattedBarcode(bean.getBarcode()))
                                .append("00102");
                    }

                    viewModel.setFacingList(facingList);
                    fop.writeFile(stringBuilder.toString(), fileName);
                    uploadFile(fileName, "");

                }
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {
                for (FacingBean bean : viewModel.getFacingList()) {
                    bean.setSendStatus(1);
                    facingRepository.updateFacing(bean, facingRepositoryListener);
                }
                finishTask(AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED);
            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onDeleteCompleted(FacingBean facingBean) {

            }

            @Override
            public void onFailed() {

            }

            @Override
            public void onFacingBeanLoaded(FacingBean facingBean) {

            }

            @Override
            public void onUpdateCompleted(FacingBean facingBean) {

            }
        };
    }

    private void setPromotionRepository() {
        promotionRepository = PromotionRepository.getInstance();
        promotionRepositoryListener = new PromotionRepository.PromotionRepositoryListener() {
            @Override
            public void onAddCompleted(PromotionBean promotionBean) {

            }

            @Override
            public void onAllListLoaded(ArrayList<PromotionBean> promotionList) {

            }

            @Override
            public void onAllSentListLoaded(ArrayList<PromotionBean> promotionList) {

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<PromotionBean> promotionList) {
                if (promotionList != null && !promotionList.isEmpty()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (PromotionBean bean : promotionList) {
                        if (promotionList.indexOf(bean) != 0) {
                            stringBuilder.append("\n");
                        }
                        stringBuilder.append("PR")
                                .append(BarcodeUtil.getFormattedBarcode(bean.getBarcode()))
                                .append("00000000")
                                .append(bean.getGondola());
                    }

                    viewModel.setPromotionList(promotionList);
                    fop.writeFile(stringBuilder.toString(), fileName);
                    uploadFile(fileName, "");

                }
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {
                for (PromotionBean bean : viewModel.getPromotionList()) {
                    bean.setSendStatus(1);
                    promotionRepository.updatePromotion(bean, promotionRepositoryListener);
                }
                finishTask(AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED);
            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onDeleteCompleted(PromotionBean promotionBean) {

            }

            @Override
            public void onFailed() {

            }

            @Override
            public void onPromotionBeanLoaded(PromotionBean promotionBean) {

            }

            @Override
            public void onUpdateCompleted(PromotionBean promotionBean) {

            }
        };
    }

    private void setOutOfStockRepository() {
        outOfStockRepository = OutOfStockRepository.getInstance();
        outOfStockRepositoryListener = new OutOfStockRepository.OutOfStockRepositoryListener() {
            @Override
            public void onAddCompleted(OutOfStockBean outOfStockBean) {

            }

            @Override
            public void onAllListLoaded(ArrayList<OutOfStockBean> outOfStockList) {

            }

            @Override
            public void onAllSentListLoaded(ArrayList<OutOfStockBean> outOfStockList) {

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<OutOfStockBean> outOfStockList) {
                if (outOfStockList != null && !outOfStockList.isEmpty()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (OutOfStockBean bean : outOfStockList) {
                        if (outOfStockList.indexOf(bean) != 0) {
                            stringBuilder.append("\n");
                        }
                        stringBuilder.append("OU")
                                .append(BarcodeUtil.getFormattedBarcode(bean.getBarcode()))
                                .append("00000000");
                    }

                    viewModel.setOutOfStockList(outOfStockList);
                    fop.writeFile(stringBuilder.toString(), fileName);
                    uploadFile(fileName, "");

                }
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {
                for (OutOfStockBean bean : viewModel.getOutOfStockList()) {
                    bean.setSendStatus(1);
                    outOfStockRepository.updateOutOfStock(bean, outOfStockRepositoryListener);
                }
                finishTask(AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED);
            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onDeleteCompleted(OutOfStockBean outOfStockBean) {

            }

            @Override
            public void onFailed() {

            }

            @Override
            public void onOutOfStockBeanLoaded(OutOfStockBean outOfStockBean) {

            }

            @Override
            public void onUpdateCompleted(OutOfStockBean outOfStockBean) {

            }
        };
    }

    private void setTransformQuantityRepository() {
        transformQuantityRepository = TransformQuantityRepository.getInstance();
        transformQuantityRepositoryListener = new TransformQuantityRepository.TransformQuantityRepositoryListener() {
            @Override
            public void onAddCompleted(TransformQuantityBean transformQuantityBean) {

            }

            @Override
            public void onAllListLoaded(ArrayList<TransformQuantityBean> transformQuantityList) {

            }

            @Override
            public void onAllSentListLoaded(ArrayList<TransformQuantityBean> transformQuantityList) {

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<TransformQuantityBean> transformQuantityList) {
                if (transformQuantityList != null && !transformQuantityList.isEmpty()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (TransformQuantityBean bean : transformQuantityList) {
                        if (transformQuantityList.indexOf(bean) != 0) {
                            stringBuilder.append("\n");
                        }
                        stringBuilder.append("IL")
                                .append(BarcodeUtil.getFormattedBarcode(bean.getBarcode()));
                    }

                    viewModel.setTransformQuantityList(transformQuantityList);
                    fop.writeFile(stringBuilder.toString(), fileName);
                    uploadFile(fileName, "");

                }
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {
                for (TransformQuantityBean bean : viewModel.getTransformQuantityList()) {
                    bean.setSendStatus(1);
                    transformQuantityRepository.updateTransformQuantity(bean, transformQuantityRepositoryListener);
                }
                finishTask(AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED);
            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onDeleteCompleted(TransformQuantityBean transformQuantityBean) {

            }

            @Override
            public void onFailed() {

            }

            @Override
            public void onTransformQuantityBeanLoaded(TransformQuantityBean transformQuantityBean) {

            }

            @Override
            public void onUpdateCompleted(TransformQuantityBean transformQuantityBean) {

            }
        };
    }

    private void setItemListRepository() {
        itemListRepository = ItemListRepository.getInstance();
        itemListRepositoryListener = new ItemListRepository.ItemListRepositoryListener() {
            @Override
            public void onAddCompleted(ItemListBean itemListBean) {

            }

            @Override
            public void onAllListLoaded(ArrayList<ItemListBean> itemListList) {

            }

            @Override
            public void onAllSentListLoaded(ArrayList<ItemListBean> itemListList) {

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<ItemListBean> itemListList) {
                if (itemListList != null && !itemListList.isEmpty()) {
                    ArrayList<ItemListBean> list = FileTransferUtil.getUniqueItemListList(itemListList);
                    StringBuilder stringBuilder = new StringBuilder();
                    for (ItemListBean bean : list) {
                        if (itemListList.indexOf(bean) != 0) {
                            stringBuilder.append("\n");
                        }
                        stringBuilder.append("IL")
                                .append(BarcodeUtil.getFormattedBarcode(bean.getBarcode()))
                                .append(BarcodeUtil.getFormattedQuantity(bean.getQuantity(), 11, true));
                    }

                    viewModel.setItemListList(itemListList);
                    fop.writeFile(stringBuilder.toString(), fileName);
                    uploadFile(fileName, "");

                }
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {
                for (ItemListBean bean : viewModel.getItemListList()) {
                    bean.setSendStatus(1);
                    itemListRepository.updateItemList(bean, itemListRepositoryListener);
                }
                finishTask(AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED);
            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onDeleteCompleted(ItemListBean itemListBean) {

            }

            @Override
            public void onFailed() {

            }

            @Override
            public void onItemListBeanLoaded(ItemListBean itemListBean) {

            }

            @Override
            public void onUpdateCompleted(ItemListBean itemListBean) {

            }
        };
    }

    private void setInternalSalesRepository() {
        internalSalesRepository = InternalSalesRepository.getInstance();
        internalSalesRepositoryListener = new InternalSalesRepository.InternalSalesRepositoryListener() {
            @Override
            public void onAddCompleted(InternalSalesBean internalSalesBean) {

            }

            @Override
            public void onAllListLoaded(ArrayList<InternalSalesBean> internalSalesList) {

            }

            @Override
            public void onAllSentListLoaded(ArrayList<InternalSalesBean> internalSalesList) {

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<InternalSalesBean> internalSalesList) {
                if (internalSalesList != null && !internalSalesList.isEmpty()) {
                    ArrayList<InternalSalesBean> list = FileTransferUtil.getUniqueInternalSaleList(internalSalesList);
                    StringBuilder stringBuilder = new StringBuilder();
                    for (InternalSalesBean bean : list) {
                        if (internalSalesList.indexOf(bean) != 0) {
                            stringBuilder.append("\n");
                        }
                        stringBuilder.append("TR")
                                .append(BarcodeUtil.getFormattedBarcode(bean.getBarcode()))
                                .append(BarcodeUtil.getFormattedQuantity(bean.getQuantity(), 11, true))
                                .append(bean.getDepartmentCode())
                                .append(bean.getSectionCode());
                    }

                    viewModel.setInternalSalesList(internalSalesList);
                    fop.writeFile(stringBuilder.toString(), fileName);
                    uploadFile(fileName, "");

                }
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {
                for (InternalSalesBean bean : viewModel.getInternalSalesList()) {
                    bean.setSendStatus(1);
                    internalSalesRepository.updateInternalSales(bean, internalSalesRepositoryListener);
                }
                finishTask(AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED);
            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onDeleteCompleted(InternalSalesBean internalSalesBean) {

            }

            @Override
            public void onFailed() {

            }

            @Override
            public void onInternalSalesBeanLoaded(InternalSalesBean internalSalesBean) {

            }

            @Override
            public void onUpdateCompleted(InternalSalesBean internalSalesBean) {

            }
        };
    }

    private void setInternalSalesCorrectionRepository() {
        internalSalesCorrectionRepository = InternalSalesCorrectionRepository.getInstance();
        internalSalesCorrectionRepositoryListener =
                new InternalSalesCorrectionRepository.InternalSalesCorrectionRepositoryListener() {
                    @Override
                    public void onAddCompleted(InternalSalesCorrectionBean internalSalesCorrectionBean) {

                    }

                    @Override
                    public void onAllListLoaded(ArrayList<InternalSalesCorrectionBean> internalSalesCorrectionList) {

                    }

                    @Override
                    public void onAllSentListLoaded(ArrayList<InternalSalesCorrectionBean> internalSalesCorrectionList) {

                    }

                    @Override
                    public void onAllUnsentListLoaded(ArrayList<InternalSalesCorrectionBean> internalSalesCorrectionList) {
                        if (internalSalesCorrectionList != null && !internalSalesCorrectionList.isEmpty()) {
                            ArrayList<InternalSalesCorrectionBean> list =
                                    FileTransferUtil.getUniqueInternalSaleCorrectionList(internalSalesCorrectionList);
                            StringBuilder stringBuilder = new StringBuilder();
                            for (InternalSalesCorrectionBean bean : list) {
                                if (internalSalesCorrectionList.indexOf(bean) != 0) {
                                    stringBuilder.append("\n");
                                }
                                stringBuilder.append("TR")
                                        .append(BarcodeUtil.getFormattedBarcode(bean.getBarcode()))
                                        .append(BarcodeUtil.getFormattedQuantity(bean.getQuantity(), 11, true))
                                        .append(bean.getDepartmentCode())
                                        .append(bean.getSectionCode());
                            }

                            viewModel.setInternalSalesCorrectionList(internalSalesCorrectionList);
                            fop.writeFile(stringBuilder.toString(), fileName);
                            uploadFile(fileName, "");

                        }
                    }

                    @Override
                    public void onDeleteAllCompleted() {

                    }

                    @Override
                    public void onDeleteAllSentCompleted() {
                        for (InternalSalesCorrectionBean bean : viewModel.getInternalSalesCorrectionList()) {
                            bean.setSendStatus(1);
                            internalSalesCorrectionRepository.updateInternalSalesCorrection(bean, internalSalesCorrectionRepositoryListener);
                        }
                        finishTask(AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED);
                    }

                    @Override
                    public void onDeleteAllUnsentCompleted() {

                    }

                    @Override
                    public void onDeleteCompleted(InternalSalesCorrectionBean internalSalesCorrectionBean) {

                    }

                    @Override
                    public void onFailed() {

                    }

                    @Override
                    public void onInternalSalesCorrectionBeanLoaded(InternalSalesCorrectionBean internalSalesCorrectionBean) {

                    }

                    @Override
                    public void onUpdateCompleted(InternalSalesCorrectionBean internalSalesCorrectionBean) {

                    }
                };
    }

    private void setPrintLabelRepository() {
        printLabelRepository = PrintLabelRepository.getInstance();
        printLabelRepositoryListener =
                new PrintLabelRepository.PrintLabelRepositoryListener() {
                    @Override
                    public void onAddCompleted(PrintLabelBean printLabelBean) {

                    }

                    @Override
                    public void onAllListLoaded(ArrayList<PrintLabelBean> printLabelList) {

                    }

                    @Override
                    public void onAllSentListLoaded(int labelType, ArrayList<PrintLabelBean> printLabelList) {

                    }

                    @Override
                    public void onAllUnsentListLoaded(int labelType, ArrayList<PrintLabelBean> printLabelList) {

                        if (printLabelList != null && !printLabelList.isEmpty()) {
                            viewModel.setPrintLabelList(printLabelList);

                            viewModel.setPrintLabelMap(new HashMap<String, java.util.ArrayList<PrintLabelBean>>());

                            for (PrintLabelBean printLabelBean : printLabelList) {
                                if (!viewModel.getPrintLabelMap().containsKey(printLabelBean.getPrinterLabel())) {
                                    viewModel.getPrintLabelMap().put(
                                            printLabelBean.getPrinterLabel(), new ArrayList<PrintLabelBean>());
                                }
                                ArrayList<PrintLabelBean> list = viewModel.getPrintLabelMap()
                                        .get(printLabelBean.getPrinterLabel());
                                viewModel.getPrintLabelMap().remove(printLabelBean.getPrinterLabel());
                                list.add(printLabelBean);
                                viewModel.getPrintLabelMap().put(printLabelBean.getPrinterLabel(), list);
                            }


                            Iterator<Map.Entry<String, ArrayList<PrintLabelBean>>> iterator =
                                    viewModel.getPrintLabelMap().entrySet().iterator();

                            while (iterator.hasNext()) {
                                Map.Entry<String, ArrayList<PrintLabelBean>> entry = iterator.next();

                                StringBuilder stringBuilder = new StringBuilder();
                                for (PrintLabelBean bean : printLabelList) {
                                    if (printLabelList.indexOf(bean) != 0) {
                                        stringBuilder.append("\n");
                                    }
                                    stringBuilder.append("ET")
                                            .append(BarcodeUtil.getFormattedBarcode(bean.getBarcode()))
                                            .append(BarcodeUtil.getFormattedQuantity(bean.getQuantity(), 3, false))
                                            .append("02");
                                }

                                viewModel.setPrintLabelList(printLabelList);
                                Log.i(TAG, "onAllUnsentListLoaded: PRINT LABEL : " + stringBuilder.toString());
                                String tempFileName = entry.getKey().equals("") ? fileName : fileName + entry.getKey();
                                fop.writeFile(stringBuilder.toString(), tempFileName);
                                uploadFile(tempFileName, entry.getKey());
                            }

                        }
                    }

                    @Override
                    public void onDeleteAllCompleted() {

                    }

                    @Override
                    public void onDeleteAllSentCompleted(String key, int labelType) {

                        viewModel.getPrintLabelProcessedList().add(key);
                        for (PrintLabelBean bean : viewModel.getPrintLabelMap().get(key)) {
                            bean.setSendStatus(1);
                            printLabelRepository.updatePrintLabel(bean, printLabelRepositoryListener);
                        }
                        if (viewModel.getPrintLabelProcessedList().size() == viewModel.getPrintLabelMap().size())
                            finishTask(AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED);
                    }

                    @Override
                    public void onDeleteAllUnsentCompleted(int labelType) {

                    }

                    @Override
                    public void onDeleteCompleted(PrintLabelBean printLabelBean) {

                    }

                    @Override
                    public void onFailed() {

                    }

                    @Override
                    public void onPrintLabelBeanLoaded(PrintLabelBean printLabelBean) {

                    }

                    @Override
                    public void onUpdateCompleted(PrintLabelBean printLabelBean) {

                    }
                };
    }


    public void onFileTransferMainMenuClick(View view) {
        view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
        //mVibrator.vibrate(25);

        /*Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);*/

        finishTask(AppConstants.FILE_TRANSFER_RESULT_FINISH);
    }

    public void onFileTransferContinueClick(View view) {
        view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
        //mVibrator.vibrate(25);

        finishTask(AppConstants.FILE_TRANSFER_RESULT_CONTINUE);
                /*Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);*/
//                if (selectedMenu.equalsIgnoreCase("6 - Merchand")) {
//                }else{
//
//                }

    }

    private void finishTask(final int fileTransferResult) {
        new PopupMessage(this)
                .show(getString(R.string.message_file_sent_successfully), 5000);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent();
                intent.putExtra("result", fileTransferResult);
                setResult(RESULT_OK, intent);
                finish();
            }
        }, 5000);

    }

    private void uploadFile(final String fileName, final String key) {
        setProgressScreenVisibility(true, true);
        FTPUploadTask ftpUploadTask = new FTPUploadTask(fop.pathEx + SENT_FILES + SEPARATOR + fileName);
        ftpUploadTask.setFTPUploadTaskListener(new FTPUploadTask.FTPUploadTaskListener() {
            @Override
            public void dataDownloadedSuccessfully(Boolean result) {
                setProgressScreenVisibility(false, false);
                switch (selectedMenuBean.getCode()) {
                    case HomeMenuUtil.CODE_IT:
                        switch (selectedSubMenuBean.getCode()) {
                            case ITMenuUtil.CODE_WASTE:
                                wasteRepository.deleteAllSentWastes(wasteRepositoryListener);
                                break;
                            case ITMenuUtil.CODE_LABEL_SURVEY:
                                labelSurveyRepository.deleteAllSentLabelSurveys(labelSurveyRepositoryListener);
                                break;
                            case ITMenuUtil.CODE_STOCK_TAKE:
                                stockTakeRepository.deleteAllSentStockTakes(stockTakeRepositoryListener);
                                break;
                            case ITMenuUtil.CODE_PRINT_LABELS:
                                printLabelRepository.deleteAllSentPrintLabels(key, labelType,
                                        printLabelRepositoryListener);
                                break;
                            case ITMenuUtil.CODE_MIN_STOCK:
                                minStockRepository.deleteAllSentMinStocks(minStockRepositoryListener);
                                break;
                            case ITMenuUtil.CODE_FACING:
                                facingRepository.deleteAllSentFacings(facingRepositoryListener);
                                break;
                            case ITMenuUtil.CODE_PROMOTION:
                                promotionRepository.deleteAllSentPromotions(promotionRepositoryListener);
                                break;
                            case ITMenuUtil.CODE_OUT_OF_STOCK:
                                outOfStockRepository.deleteAllSentOutOfStocks(outOfStockRepositoryListener);
                                break;
                            case ITMenuUtil.CODE_TRANSFORM_QUANTITY:
                                transformQuantityRepository.deleteAllSentTransformQuantitys(transformQuantityRepositoryListener);
                                break;
                            case ITMenuUtil.CODE_ITEM_LIST:
                                itemListRepository.deleteAllSentItemLists(itemListRepositoryListener);
                                break;
                            case ITMenuUtil.CODE_INTERNAL_SALES:
                                internalSalesRepository.deleteAllSentInternalSales(internalSalesRepositoryListener);
                                break;
                            case ITMenuUtil.CODE_INTERNAL_SALES_CORRECT:
                                internalSalesCorrectionRepository.deleteAllSentInternalSalesCorrection(
                                        internalSalesCorrectionRepositoryListener);
                                break;
                            case ITMenuUtil.CODE_EXIT:
                                break;
                        }
                        break;
                    case HomeMenuUtil.CODE_RECEIVE:
                        break;
                    case HomeMenuUtil.CODE_ELIE:
                        break;
                    case HomeMenuUtil.CODE_ORDERS:
                        break;
                    case HomeMenuUtil.CODE_INFO:
                        break;
                    case HomeMenuUtil.CODE_MERCHAND:
                        break;
                    case HomeMenuUtil.CODE_FOOD_BANK:
                        break;
                }
            }

            @Override
            public void dataDownloadFailed() {
                setProgressScreenVisibility(false, false);
                ConfirmationDialog confirmationDialog = new ConfirmationDialog(FileTransferActivity.this);
                confirmationDialog.setConfirmationDialogActionListener(
                        new ConfirmationDialog.ConfirmationDialogActionListener() {
                            @Override
                            public void onYesClicked() {
                                uploadFile(fileName, key);
                            }

                            @Override
                            public void onNoClicked() {
                                finishTask(AppConstants.FILE_TRANSFER_RESULT_CONTINUE);
                            }
                        });
                confirmationDialog.show(R.string.message_file_upload_failed);
            }

        });
        ftpUploadTask.execute();
    }

    public void onFileTransferSendDataClick(View view) {
        view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
        //mVibrator.vibrate(25);

        // TODO: 22-07-2018 SEND DATA TO SERVER

        switch (selectedMenuBean.getCode()) {
            case HomeMenuUtil.CODE_IT:
                sendDataIT();
                break;
            case HomeMenuUtil.CODE_RECEIVE:
                break;
            case HomeMenuUtil.CODE_ELIE:
                break;
            case HomeMenuUtil.CODE_ORDERS:
                break;
            case HomeMenuUtil.CODE_INFO:
                break;
            case HomeMenuUtil.CODE_MERCHAND:
                break;
            case HomeMenuUtil.CODE_FOOD_BANK:
                break;
        }

//        finishTask(AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED);

    }


    private void sendDataIT() {
        switch (selectedSubMenuBean.getCode()) {
            case ITMenuUtil.CODE_WASTE:
                wasteRepository.getAllUnsentWastes(wasteRepositoryListener);
                break;

            case ITMenuUtil.CODE_LABEL_SURVEY:
                labelSurveyRepository.getAllUnsentLabelSurveys(labelSurveyRepositoryListener);
                break;

            case ITMenuUtil.CODE_STOCK_TAKE:
                startActivityForResult(new Intent(this, PitNumberActivity.class), REQ_PIT_NUMBER);
                break;

            case ITMenuUtil.CODE_PRINT_LABELS:
                printLabelRepository.getAllUnsentPrintLabels(labelType, printLabelRepositoryListener);
                break;

            case ITMenuUtil.CODE_MIN_STOCK:
                minStockRepository.getAllUnsentMinStocks(minStockRepositoryListener);
                break;

            case ITMenuUtil.CODE_FACING:
                facingRepository.getAllUnsentFacings(facingRepositoryListener);
                break;

            case ITMenuUtil.CODE_PROMOTION:
                promotionRepository.getAllUnsentPromotions(promotionRepositoryListener);
                break;

            case ITMenuUtil.CODE_OUT_OF_STOCK:
                outOfStockRepository.getAllUnsentOutOfStocks(outOfStockRepositoryListener);
                break;

            case ITMenuUtil.CODE_TRANSFORM_QUANTITY:
                transformQuantityRepository.getAllUnsentTransformQuantities(transformQuantityRepositoryListener);
                break;

            case ITMenuUtil.CODE_ITEM_LIST:
                itemListRepository.getAllUnsentItemLists(itemListRepositoryListener);
                break;

            case ITMenuUtil.CODE_INTERNAL_SALES:
                internalSalesRepository.getAllUnsentInternalSales(internalSalesRepositoryListener);
                break;
            case ITMenuUtil.CODE_INTERNAL_SALES_CORRECT:
                internalSalesCorrectionRepository.getAllUnsentInternalSalesCorrection(internalSalesCorrectionRepositoryListener);
                break;
            case ITMenuUtil.CODE_EXIT:
                break;
        }

    }
}
