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.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.dbUtils.repositories.StockTakeRepository;
import in.techware.carrefour.dialogs.ConfirmationDialog;
import in.techware.carrefour.listeners.BarcodeUpdateListener;
import in.techware.carrefour.model.MenuBean;
import in.techware.carrefour.model.StockTakeBean;
import in.techware.carrefour.util.AppConstants;
import in.techware.carrefour.util.BarcodeUtil;
import in.techware.carrefour.viewModels.StockTakeViewModel;

public class StockTakeActivity extends BaseAppCompatNoDrawerActivity {

    private static final String TAG = "StockTakeA";
    private CheckBox cbQuantity;
    private EditText etxtQuantity;
    private EditText etxtZoneType;
    private EditText etxtBarcode;
    private Button btnChange;
    private Button btnBack;
    private Button btnModify;
    private Button btnDelete;
    private MenuBean selectedMenuBean;
    private MenuBean selectedSubMenuBean;
    private StockTakeViewModel viewModel;
    private TextView txtLastEntryBarcode;
    private TextView txtLastEntryQuantity;
    private StockTakeRepository stockTakeRepository;
    private StockTakeRepository.StockTakeRepositoryListener stockTakeRepositoryListener;
    private View.OnClickListener clickListener;

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

        if (getIntent().hasExtra("menuBean")) {
            selectedMenuBean = (MenuBean) getIntent().getSerializableExtra("menuBean");
        }
        if (getIntent().hasExtra("subMenuBean")) {
            selectedSubMenuBean = (MenuBean) getIntent().getSerializableExtra("subMenuBean");
        }

        viewModel = (StockTakeViewModel) ViewModelProviders.of(this).get(StockTakeViewModel.class);
        viewModel.setSelectedMenuBean(selectedMenuBean);
        viewModel.setSelectedSubMenuBean(selectedSubMenuBean);

        initViews();

        handleKeyboard();

        populateViewModel();

        if (getSupportActionBar() != null) {
            setTitle(R.string.title_stock_take, R.color.white);
            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.getStockTakeList().isEmpty()) {
            setProgressScreenVisibility(true, true);
            getData(false);
        } else {
            getData(true);
        }

    }

    private void getData(boolean isSwipeRefreshing) {
        swipeView.setRefreshing(isSwipeRefreshing);
        StockTakeRepository.getInstance().getAllUnsentStockTakes(stockTakeRepositoryListener);
    }


    @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);
                onStockTakeBackClick(toolbar);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initViews() {
        cbQuantity = findViewById(R.id.cb_stock_take_quantity);
        etxtQuantity = findViewById(R.id.etxt_stock_take_quantity);
        etxtZoneType = findViewById(R.id.etxt_stock_take_type);
        etxtBarcode = findViewById(R.id.etxt_stock_take_barcode);

        txtLastEntryBarcode = findViewById(R.id.txt_stock_take_last_entry_barcode);
        txtLastEntryQuantity = findViewById(R.id.txt_stock_take_last_entry_quantity);

        btnChange = findViewById(R.id.btn_stock_take_change);
        btnBack = findViewById(R.id.btn_stock_take_back);
        btnModify = findViewById(R.id.btn_stock_take_modify);
        btnDelete = findViewById(R.id.btn_stock_take_delete);

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onStockTakeBackClick(v);
            }
        });
        btnChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onStockTakeChangeClick(v);
            }
        });
        btnModify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onStockTakeModifyClick(v);
            }
        });
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onStockTakeDeleteClick(v);
            }
        });


        stockTakeRepository = StockTakeRepository.getInstance();

        stockTakeRepositoryListener = new StockTakeRepository.StockTakeRepositoryListener() {
            @Override
            public void onAddCompleted(StockTakeBean stockTakeBean) {
                viewModel.getStockTakeList().add(stockTakeBean);
                onSaveCompleted();
            }

            @Override
            public void onDeleteCompleted(StockTakeBean stockTakeBean) {
                int index = viewModel.indexOf(stockTakeBean);
                if (index != -1)
                    viewModel.getStockTakeList().remove(index);
                populateViewModel();
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {

            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onUpdateCompleted(StockTakeBean stockTakeBean) {
                int index = viewModel.indexOf(stockTakeBean);
                if (index != -1) {
                    viewModel.getStockTakeList().set(index, stockTakeBean);
                    onSaveCompleted();
                }
            }

            @Override
            public void onStockTakeBeanLoaded(StockTakeBean stockTakeBean) {

            }

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

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<StockTakeBean> stockTakeList) {
                viewModel.setStockTakeList(stockTakeList);
                populateViewModel();
                swipeView.setRefreshing(false);
                setProgressScreenVisibility(false, false);
            }

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

            }

            @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");
                }*/
            }
        });

        etxtZoneType.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_UP) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    if (!etxtZoneType.getText().toString().equals("")) {
                        v.clearFocus();
                        viewModel.setZoneType(etxtZoneType.getText().toString());
                        populateViewModel();
                    }

                    return true;
                }

                return false;
            }
        });

        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()) {
                        saveStockTakeBean();
                    } 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 > 1000) {
                            ConfirmationDialog confirmationDialog =
                                    new ConfirmationDialog(StockTakeActivity.this);
                            confirmationDialog.setConfirmationDialogActionListener(
                                    new ConfirmationDialog.ConfirmationDialogActionListener() {
                                        @Override
                                        public void onYesClicked() {
                                            viewModel.setQuantity(quantity);
                                            //                                            viewModel.setQuantityEnabled(false);
                                            if (viewModel.isDataCollected()) {
                                                saveStockTakeBean();
                                            }
                                        }

                                        @Override
                                        public void onNoClicked() {
                                            viewModel.setQuantity(1);
                                            //                                            viewModel.setQuantityEnabled(false);
                                            if (viewModel.isDataCollected()) {
                                                saveStockTakeBean();
                                            }
                                        }
                                    });
                            confirmationDialog.show(R.string.message_quantity_is_greater_than_1000);
                        } else {
                            viewModel.setQuantity(quantity);
                            //                            viewModel.setQuantityEnabled(false);
                            if (viewModel.isDataCollected()) {
                                saveStockTakeBean();
                            }
                        }
                    }
                    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()) {
                    saveStockTakeBean();
                } else if (viewModel.isQuantityEnabled()) {
                    etxtQuantity.requestFocus();
                }
            }
        };
        addBarcodeUpdateListener(barcodeUpdateListener);
    }

    private void onSaveCompleted() {
        viewModel.clearStockTake();
        viewModel.setLastEntry(viewModel.getStockTakeList().get(viewModel.lastIndex()));
        viewModel.setModifyEnabled(false);
        populateViewModel();
        etxtZoneType.performClick();
        etxtZoneType.requestFocus();
    }

    private void handleKeyboard() {

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

    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));

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

        cbQuantity.setChecked(viewModel.isQuantityEnabled());

        if (!viewModel.getZoneType().equals("")) {
            enableViews(true);
        } else {
            enableViews(false);
        }

        if (!viewModel.getStockTakeList().isEmpty()) {
            viewModel.setLastEntry(viewModel.getStockTakeList().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.getStockTakeList().size() > 0) {
            btnModify.setEnabled(true);
            btnDelete.setEnabled(true);
        } else {
            btnModify.setEnabled(false);
            btnDelete.setEnabled(false);
        }
    }

    private void saveStockTakeBean() {
        StockTakeBean stockTakeBean = viewModel.generateStockTakeBean();

        if (viewModel.isModifyEnabled()) {
            stockTakeBean.setId(viewModel.getLastEntry().getId());
            stockTakeRepository.updateStockTake(stockTakeBean, stockTakeRepositoryListener);
        } else {
            stockTakeRepository.insertStockTake(stockTakeBean, stockTakeRepositoryListener);
        }
    }

    private void enableViews(boolean isEnable) {

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

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

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


        etxtZoneType.setEnabled(!isEnable);
        etxtZoneType.setFocusable(!isEnable);
        etxtZoneType.setFocusableInTouchMode(!isEnable);
        etxtZoneType.setTextIsSelectable(!isEnable);
        if (!isEnable)
            etxtZoneType.requestFocus();

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

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

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

    public void onStockTakeModifyClick(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 onStockTakeDeleteClick(View view) {
        view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
        //mVibrator.vibrate(25);

        if (!viewModel.getStockTakeList().isEmpty() && viewModel.getLastEntry() != null) {
            stockTakeRepository.deleteStockTake(
                    viewModel.getLastEntry()
                    , stockTakeRepositoryListener);
        }

    }

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

        enableViews(false);
        etxtZoneType.requestFocus();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onStockTakeBackClick(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;
    }
}
