package in.techware.carrefour.activity.it;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.ArrayList;

import in.techware.carrefour.R;
import in.techware.carrefour.activity.BaseAppCompatNoDrawerActivity;
import in.techware.carrefour.activity.FileTransferActivity;
import in.techware.carrefour.config.Config;
import in.techware.carrefour.dbUtils.repositories.PrintLabelRepository;
import in.techware.carrefour.dialogs.ConfirmationDialog;
import in.techware.carrefour.dialogs.SelectDialog;
import in.techware.carrefour.listeners.BarcodeUpdateListener;
import in.techware.carrefour.model.BasicDataBean;
import in.techware.carrefour.model.MenuBean;
import in.techware.carrefour.model.PrintLabelBean;
import in.techware.carrefour.model.PrinterBean;
import in.techware.carrefour.util.AppConstants;
import in.techware.carrefour.util.BarcodeUtil;
import in.techware.carrefour.viewModels.PrintLabelViewModel;

public class PrintLabelActivity extends BaseAppCompatNoDrawerActivity {

    private static final String TAG = "PrintLabelA";
    private CheckBox cbPrinter;
    private LinearLayout llSelectPrinter;
    private TextView txtSelectPrinter;
    private CheckBox cbQuantity;
    private EditText etxtQuantity;
    private EditText etxtBarcode;
    private Button btnBack;
    private Button btnModify;
    private Button btnDelete;
    private MenuBean selectedMenuBean;
    private MenuBean selectedSubMenuBean;
    private int labelType = 0;
    private PrinterBean printerBean;
    private PrintLabelViewModel viewModel;
    private TextView txtLastEntryBarcode;
    private TextView txtLastEntryQuantity;
    private PrintLabelRepository printLabelRepository;
    private PrintLabelRepository.PrintLabelRepositoryListener printLabelRepositoryListener;
    private View.OnClickListener clickListener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_print_label);

        if (getIntent().hasExtra("menuBean")) {
            selectedMenuBean = (MenuBean) getIntent().getSerializableExtra("menuBean");
        }
        if (getIntent().hasExtra("subMenuBean")) {
            selectedSubMenuBean = (MenuBean) getIntent().getSerializableExtra("subMenuBean");
        }
        if (getIntent().hasExtra("labelType")) {
            labelType = getIntent().getIntExtra("labelType", 0);
        }
        if (getIntent().hasExtra("printerBean")) {
            printerBean = (PrinterBean) getIntent().getSerializableExtra("printerBean");
        }

        viewModel = (PrintLabelViewModel) ViewModelProviders.of(this).get(PrintLabelViewModel.class);
        viewModel.setSelectedMenuBean(selectedMenuBean);
        viewModel.setSelectedSubMenuBean(selectedSubMenuBean);
        viewModel.setLabelType(labelType);
        viewModel.setPrinterBean(printerBean);

        initViews();

        handleKeyboard();

        populateViewModel();

        if (getSupportActionBar() != null) {
            switch (labelType) {
                case AppConstants.LABEL_TYPE_INVENTORY_LABEL:
                    setTitle(R.string.title_inventory_label, R.color.white);
                    break;
                case AppConstants.LABEL_TYPE_IT_LABEL:
                    setTitle(R.string.title_it_label, R.color.white);
                    break;
                case AppConstants.LABEL_TYPE_SHELF_LABEL:
                    setTitle(R.string.title_shelf_label, R.color.white);
                    break;
            }
            getSupportActionBar().setTitle("");
            getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(true);
        }

    }

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

        if (requestCode == REQ_FILE_TRANSFER && resultCode == RESULT_OK) {
            if (data != null && data.hasExtra("result")) {
                if (data.getIntExtra("result", 0) == AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED) {
                    finish();
                }
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();

        if (viewModel.getPrintLabelList().isEmpty()) {
            setProgressScreenVisibility(true, true);
            getData(false);
        } else {
            getData(true);
        }

    }

    private void getData(boolean isSwipeRefreshing) {
        swipeView.setRefreshing(isSwipeRefreshing);
        PrintLabelRepository.getInstance().getAllUnsentPrintLabels(printLabelRepositoryListener);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_base, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                toolbar.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
                //                mVibrator.vibrate(25);
                onPrintLabelBackClick(toolbar);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initViews() {
        cbQuantity = findViewById(R.id.cb_print_label_quantity);
        etxtQuantity = findViewById(R.id.etxt_print_label_quantity);
        etxtBarcode = findViewById(R.id.etxt_print_label_barcode);

        llSelectPrinter = findViewById(R.id.ll_print_label_printer);
        txtSelectPrinter = findViewById(R.id.txt_print_label_printer);
//        cbPrinter = findViewById(R.id.cb_print_label_quantity);

        txtLastEntryBarcode = findViewById(R.id.txt_print_label_last_entry_barcode);
        txtLastEntryQuantity = findViewById(R.id.txt_print_label_last_entry_quantity);

        btnBack = findViewById(R.id.btn_print_label_back);
        btnModify = findViewById(R.id.btn_print_label_modify);
        btnDelete = findViewById(R.id.btn_print_label_delete);

        llSelectPrinter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPrintLabelPrinterClick(v);
            }
        });

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPrintLabelBackClick(v);
            }
        });
        btnModify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPrintLabelModifyClick(v);
            }
        });
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPrintLabelDeleteClick(v);
            }
        });


        printLabelRepository = PrintLabelRepository.getInstance();

        printLabelRepositoryListener = new PrintLabelRepository.PrintLabelRepositoryListener() {
            @Override
            public void onAddCompleted(PrintLabelBean printLabelBean) {
                viewModel.getPrintLabelList().add(printLabelBean);
                onSaveCompleted();
            }

            @Override
            public void onDeleteCompleted(PrintLabelBean printLabelBean) {
                int index = viewModel.indexOf(printLabelBean);
                if (index != -1)
                    viewModel.getPrintLabelList().remove(index);
                populateViewModel();
            }

            @Override
            public void onDeleteAllCompleted() {

            }

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

            }

            @Override
            public void onDeleteAllUnsentCompleted(int labelType) {

            }

            @Override
            public void onUpdateCompleted(PrintLabelBean printLabelBean) {
                int index = viewModel.indexOf(printLabelBean);
                if (index != -1) {
                    viewModel.getPrintLabelList().set(index, printLabelBean);
                    onSaveCompleted();
                }
            }

            @Override
            public void onPrintLabelBeanLoaded(PrintLabelBean printLabelBean) {

            }

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

            }

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

            }

            @Override
            public void onAllUnsentListLoaded(int labelType, ArrayList<PrintLabelBean> printLabelList) {
                viewModel.setPrintLabelList(printLabelList);
                populateViewModel();
                swipeView.setRefreshing(false);
                setProgressScreenVisibility(false, false);
            }

            @Override
            public void onFailed() {

            }
        };

        etxtQuantity.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.i(TAG, "onTouch: etxtQuantity isEnabled : " + etxtQuantity.isEnabled());
                if (viewModel.isQuantityEnabled() && etxtQuantity.isEnabled() && !etxtQuantity.hasFocus()) {
                    etxtQuantity.requestFocus();
                }
                return false;
            }
        });

        etxtQuantity.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.i(TAG, "onFocusChange: QUANTITY FOCUS : " + hasFocus);
                if (hasFocus) {
                    etxtQuantity.setText("");
                } /*else {
                    etxtQuantity.setText("1");
                }*/
            }
        });

        etxtBarcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_UP) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    String barcode = etxtBarcode.getText().toString();
                    etxtBarcode.setText(BarcodeUtil.getFormattedBarcode(barcode));
                    viewModel.setBarcode(barcode);

                    if (viewModel.isDataCollected() && !viewModel.isQuantityEnabled()) {
                        savePrintLabelBean();
                    } else if (viewModel.isQuantityEnabled()) {
                        etxtQuantity.requestFocus();
                    }

                    return true;
                }

                return false;
            }
        });
        etxtQuantity.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_UP) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    Log.i(TAG, "onEditorAction: " + etxtQuantity.getText().toString());
                    if (etxtQuantity.getText().toString().length() > 0) {
                        final float quantity = Float.parseFloat(etxtQuantity.getText().toString());
                        if (quantity > 99) {
                            ConfirmationDialog confirmationDialog =
                                    new ConfirmationDialog(PrintLabelActivity.this);
                            confirmationDialog.setConfirmationDialogActionListener(
                                    new ConfirmationDialog.ConfirmationDialogActionListener() {
                                        @Override
                                        public void onYesClicked() {
                                            viewModel.setQuantity(quantity);
                                            //                                            viewModel.setQuantityEnabled(false);
                                            if (viewModel.isDataCollected()) {
                                                savePrintLabelBean();
                                            }
                                        }

                                        @Override
                                        public void onNoClicked() {
                                            viewModel.setQuantity(1);
                                            //                                            viewModel.setQuantityEnabled(false);
                                            if (viewModel.isDataCollected()) {
                                                savePrintLabelBean();
                                            }
                                        }
                                    });
                            confirmationDialog.show(R.string.message_quantity_is_greater_than_99);
                        } else {
                            viewModel.setQuantity(quantity);
                            //                            viewModel.setQuantityEnabled(false);
                            if (viewModel.isDataCollected()) {
                                savePrintLabelBean();
                            }
                        }
                    }
                    return true;
                }

                return false;
            }
        });


        cbQuantity.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.i(TAG, "onCheckedChanged: CHECKED STATUS : " + isChecked);
                etxtQuantity.setEnabled(isChecked);
                etxtQuantity.setTextIsSelectable(isChecked);
                etxtQuantity.setFocusable(isChecked);
                etxtQuantity.setFocusableInTouchMode(isChecked);

                viewModel.setQuantity(1);
                viewModel.setQuantityEnabled(isChecked);
                etxtQuantity.setText(!isChecked ? "" : BarcodeUtil.removeTrailingZeroes(viewModel.getQuantity()));
                if (isChecked) {
                    etxtQuantity.requestFocus();
                } else {
                    etxtQuantity.clearFocus();
                }
//                populateViewModel();
            }
        });

        BarcodeUpdateListener barcodeUpdateListener = new BarcodeUpdateListener() {
            @Override
            public void onBarcodeUpdated(String barcode) {
                etxtBarcode.setText(barcode);
                viewModel.setBarcode(barcode);
                if (viewModel.isDataCollected() && !viewModel.isQuantityEnabled()) {
                    savePrintLabelBean();
                } else if (viewModel.isQuantityEnabled()) {
                    etxtQuantity.requestFocus();
                }
            }
        };
        addBarcodeUpdateListener(barcodeUpdateListener);
    }

    private void onSaveCompleted() {
        viewModel.clearPrintLabel();
        viewModel.setLastEntry(viewModel.getPrintLabelList().get(viewModel.lastIndex()));
        viewModel.setModifyEnabled(false);
        populateViewModel();
    }

    private void handleKeyboard() {

        if (getSharedPreferences(AppConstants.PREF_FILE, 0).getBoolean(AppConstants.KEYBOARD_STATUS, false)) {
            etxtBarcode.setFocusableInTouchMode(true);
            etxtQuantity.setFocusableInTouchMode(true);
        } else {
//            etxtZoneType.setOnFocusChangeListener(focusChangedListener);
//            etxtBarcode.setOnFocusChangeListener(focusChangedListener);
//            etxtQuantity.setOnFocusChangeListener(focusChangedListener);
            etxtBarcode.setFocusableInTouchMode(false);
            etxtQuantity.setFocusableInTouchMode(false);
            setClickListener(etxtQuantity);
            setClickListener(etxtBarcode);
        }
    }

    private void setClickListener(final EditText etxt) {
        clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etxt.setEnabled(true);
                etxt.setTextIsSelectable(true);
                etxt.setFocusable(true);
                etxt.setFocusableInTouchMode(true);

                if (etxt.isEnabled() && !etxt.hasFocus()) {
                    etxt.requestFocus();
                }

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        };
    }

    private void populateViewModel() {

        Log.i(TAG, "populateViewModel: VIEW MODEL : " + new Gson().toJson(viewModel));

        etxtBarcode.setText(!viewModel.isModifyEnabled() ? viewModel.getBarcode() : BarcodeUtil.getFormattedBarcode(viewModel.getBarcode()));
        etxtQuantity.setText(!viewModel.isModifyEnabled() ? "" : BarcodeUtil.removeTrailingZeroes(viewModel.getQuantity()));

        cbQuantity.setChecked(viewModel.isQuantityEnabled());

        if (viewModel.getPrinterBean() != null) {
            enableViews(true);
        } else {
            enableViews(false);
        }

        if (!viewModel.getPrintLabelList().isEmpty()) {
            viewModel.setLastEntry(viewModel.getPrintLabelList().get(viewModel.lastIndex()));
        } else {
            viewModel.setLastEntry(null);
        }
        if (viewModel.getLastEntry() != null) {
            txtLastEntryBarcode.setText(viewModel.getLastEntry().getBarcode());
            txtLastEntryQuantity.setText(BarcodeUtil.removeTrailingZeroes(viewModel.getLastEntry().getQuantity()));
        } else {
            txtLastEntryBarcode.setText("");
            txtLastEntryQuantity.setText("");
        }

        if (viewModel.getPrintLabelList().size() > 0) {
            btnModify.setEnabled(true);
            btnDelete.setEnabled(true);
        } else {
            btnModify.setEnabled(false);
            btnDelete.setEnabled(false);
        }

    }


    private void enableViews(boolean isEnable) {

        llSelectPrinter.setEnabled(!isEnable);

        cbQuantity.setEnabled(isEnable);
        etxtQuantity.setEnabled(viewModel.isQuantityEnabled() && isEnable);
        etxtBarcode.setEnabled(isEnable);

        cbQuantity.setFocusable(isEnable);
        etxtQuantity.setFocusable(viewModel.isQuantityEnabled() && isEnable);
        etxtBarcode.setFocusable(isEnable);

        etxtBarcode.setTextIsSelectable(isEnable);
        etxtBarcode.setFocusableInTouchMode(isEnable);
        etxtQuantity.setTextIsSelectable(viewModel.isQuantityEnabled() && isEnable);
        etxtQuantity.setFocusableInTouchMode(viewModel.isQuantityEnabled() && isEnable);

        if (isEnable && !etxtBarcode.hasFocus()) {
            etxtBarcode.requestFocus();
        }
    }


    private void savePrintLabelBean() {
        PrintLabelBean printLabelBean = viewModel.generatePrintLabelBean();

        if (viewModel.isModifyEnabled()) {
            printLabelBean.setId(viewModel.getLastEntry().getId());
            printLabelRepository.updatePrintLabel(printLabelBean, printLabelRepositoryListener);
        } else {
            printLabelRepository.insertPrintLabel(printLabelBean, printLabelRepositoryListener);
        }
    }

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

        if (Config.getInstance().getBasicDataBean() == null) {
            Config.getInstance().setBasicDataBean(new BasicDataBean());
        }
        Config.getInstance().getBasicDataBean().setPrinterList(viewModel.getPrinterList());

        SelectDialog selectDialog = new SelectDialog(this,
                AppConstants.ACTION_CHOOSE_PRINTER);
        selectDialog.setTitle(getString(R.string.label_select_printer));
        selectDialog.setSelectDialogActionListener(new SelectDialog.SelectDialogActionListener() {
            @Override
            public void actionCompletedSuccessfully(int position, String value) {

                txtSelectPrinter.setText(value);
                viewModel.setPrinterBean(viewModel.getPrinterList().get(position));
                viewModel.setPrinterSelectedPosition(position);
                populateViewModel();
            }

            @Override
            public void actionFailed(String errorMsg) {
                populateViewModel();
            }
        });
        selectDialog.show();

    }

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

        if (!viewModel.getPrintLabelList().isEmpty()) {
            startActivityForResult(new Intent(getApplicationContext(), FileTransferActivity.class)
                    .putExtra("menuBean", selectedMenuBean)
                    .putExtra("subMenuBean", selectedSubMenuBean)
                    .putExtra("labelType", labelType), REQ_FILE_TRANSFER);
        } else {
            finish();
        }
    }

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

        if (viewModel.getLastEntry() != null) {
            viewModel.setModifyEnabled(true);
            viewModel.setModifiedID(viewModel.getLastEntry().getId());
            viewModel.setData(viewModel.getLastEntry());
            populateViewModel();
        }

    }

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

        if (!viewModel.getPrintLabelList().isEmpty() && viewModel.getLastEntry() != null) {
            printLabelRepository.deletePrintLabel(viewModel.getLastEntry(), printLabelRepositoryListener);
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onPrintLabelBackClick(toolbar);
            return true;
        }

        if (keyCode == KeyEvent.KEYCODE_MENU) {
            openOptionsMenu();
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
            // TODO: 22-07-2018 Do Things On Enter Click
            Toast.makeText(this, "EnterClicked", Toast.LENGTH_SHORT).show();
            return false;
        }
        return false;
    }
}
