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.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
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.MinStockRepository;
import in.techware.carrefour.dialogs.ConfirmationDialog;
import in.techware.carrefour.listeners.BarcodeUpdateListener;
import in.techware.carrefour.model.MenuBean;
import in.techware.carrefour.model.MinStockBean;
import in.techware.carrefour.util.AppConstants;
import in.techware.carrefour.util.BarcodeUtil;
import in.techware.carrefour.viewModels.MinStockViewModel;

public class MinStockActivity extends BaseAppCompatNoDrawerActivity {

    private static final String TAG = "MinStockA";
    private EditText etxtQuantity;
    private EditText etxtBarcode;
    private Button btnBack;
    private Button btnModify;
    private MenuBean selectedMenuBean;
    private MenuBean selectedSubMenuBean;
    private MinStockViewModel viewModel;
    private TextView txtLastEntryBarcode;
    private TextView txtLastEntryQuantity;
    private MinStockRepository minStockRepository;
    private MinStockRepository.MinStockRepositoryListener minStockRepositoryListener;
    private View.OnClickListener clickListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_min_stock);
        if (getIntent().hasExtra("menuBean")) {
            selectedMenuBean = (MenuBean) getIntent().getSerializableExtra("menuBean");
        }
        if (getIntent().hasExtra("subMenuBean")) {
            selectedSubMenuBean = (MenuBean) getIntent().getSerializableExtra("subMenuBean");
        }

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

        initViews();

        handleKeyboard();

        populateViewModel();

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

    }

    private void getData(boolean isSwipeRefreshing) {
        swipeView.setRefreshing(isSwipeRefreshing);
        minStockRepository.getAllUnsentMinStocks(minStockRepositoryListener);
    }


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


    private void initViews() {

        etxtQuantity = findViewById(R.id.etxt_min_stock_quantity);
        etxtBarcode = findViewById(R.id.etxt_min_stock_barcode);

        txtLastEntryBarcode = findViewById(R.id.txt_min_stock_last_entry_barcode);
        txtLastEntryQuantity = findViewById(R.id.txt_min_stock_last_entry_quantity);

        btnBack = findViewById(R.id.btn_min_stock_back);
        btnModify = findViewById(R.id.btn_min_stock_modify);

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

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

        minStockRepository = MinStockRepository.getInstance();

        minStockRepositoryListener = new MinStockRepository.MinStockRepositoryListener() {
            @Override
            public void onAddCompleted(MinStockBean minStockBean) {
                viewModel.getMinStockList().add(minStockBean);
                onSaveCompleted();
            }

            @Override
            public void onDeleteCompleted(MinStockBean minStockBean) {
                int index = viewModel.indexOf(minStockBean);
                if (index != -1)
                    viewModel.getMinStockList().remove(index);
                onSaveCompleted();
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {

            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onUpdateCompleted(MinStockBean minStockBean) {
                int index = viewModel.indexOf(minStockBean);
                if (index != -1) {
                    viewModel.getMinStockList().set(index, minStockBean);
                    onSaveCompleted();
                }
            }

            @Override
            public void onMinStockBeanLoaded(MinStockBean minStockBean) {

            }

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

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<MinStockBean> minStockList) {
                viewModel.setMinStockList(minStockList);
                populateViewModel();
                etxtBarcode.requestFocus();
                etxtBarcode.performClick();
                swipeView.setRefreshing(false);
                setProgressScreenVisibility(false, false);
            }

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

            }

            @Override
            public void onFailed() {

            }
        };

        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");
                }*/
            }
        });
        etxtQuantity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etxtQuantity.getText().toString().length() > 0) {
                    float value = Float.parseFloat(etxtQuantity.getText().toString());
                    if (value > 99999.999) {
                        etxtQuantity.setText(R.string.sample_max_quantity);
                    } else if (value < 1) {
                        etxtQuantity.setText("1");
                    }

                    Log.i(TAG, "afterTextChanged: Formatted Quantity : " + BarcodeUtil.getFormattedQuantity(value, 8, true));
                }
            }

        });

        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);
                    populateViewModel();
                    etxtQuantity.requestFocus();

                    return true; // consume.
                }
                return false; // pass on to other listeners.
            }
        });
        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(MinStockActivity.this);
                            confirmationDialog.setConfirmationDialogActionListener(
                                    new ConfirmationDialog.ConfirmationDialogActionListener() {
                                        @Override
                                        public void onYesClicked() {
                                            viewModel.setQuantity(quantity);
//                            viewModel.setQuantityEnabled(false);
                                            if (viewModel.isDataCollected()) {
                                                saveMinStockBean();
                                            }
                                        }

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

                    }
                    return true; // consume.
                }
                return false; // pass on to other listeners.
            }
        });

        BarcodeUpdateListener barcodeUpdateListener = new BarcodeUpdateListener() {
            @Override
            public void onBarcodeUpdated(String barcode) {
                etxtBarcode.setText(barcode);
                viewModel.setBarcode(barcode);
                populateViewModel();
                etxtQuantity.requestFocus();
            }
        };
        addBarcodeUpdateListener(barcodeUpdateListener);
    }

    private void onSaveCompleted() {
        viewModel.clearMinStock();
        viewModel.setLastEntry(viewModel.getMinStockList().get(viewModel.lastIndex()));
        viewModel.setModifyEnabled(false);
        populateViewModel();
        etxtBarcode.performClick();
        etxtBarcode.requestFocus();
    }

    private void handleKeyboard() {

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

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

        etxtQuantity.setFocusable(true);
        etxtQuantity.setEnabled(true);

        enableViews(true);

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

    }

    private void enableViews(boolean isEnable) {
        etxtQuantity.setEnabled(isEnable);
        etxtBarcode.setEnabled(isEnable);

        etxtQuantity.setFocusable(isEnable);
        etxtBarcode.setFocusable(isEnable);

        etxtBarcode.setTextIsSelectable(isEnable);
        etxtBarcode.setFocusableInTouchMode(isEnable);
        etxtQuantity.setTextIsSelectable(isEnable);
        etxtQuantity.setFocusableInTouchMode(isEnable);
    }

    private void saveMinStockBean() {
        MinStockBean minStockBean = viewModel.generateMinStockBean();

        if (viewModel.isModifyEnabled()) {
            minStockRepository.updateMinStock(minStockBean, minStockRepositoryListener);
        } else {
            if (viewModel.indexOf(minStockBean) >= 0) {
                MinStockBean oldMinStockBean = viewModel.getMinStockList().get(viewModel.indexOf(minStockBean));
                minStockBean.setQuantity(minStockBean.getQuantity() - oldMinStockBean.getQuantity());
                minStockRepository.updateMinStock(minStockBean, minStockRepositoryListener);
            } else {
                minStockRepository.insertMinStock(minStockBean, minStockRepositoryListener);
            }
        }
    }

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

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

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

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

    }

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