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.EditorInfo;
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.LabelSurveyRepository;
import in.techware.carrefour.listeners.BarcodeUpdateListener;
import in.techware.carrefour.model.LabelSurveyBean;
import in.techware.carrefour.model.MenuBean;
import in.techware.carrefour.util.AppConstants;
import in.techware.carrefour.util.BarcodeUtil;
import in.techware.carrefour.viewModels.LabelSurveyViewModel;

public class LabelSurveyActivity extends BaseAppCompatNoDrawerActivity {

    private static final String TAG = "LabelSurveyA";
    private EditText etxtSection;
    private EditText etxtPrice;
    private EditText etxtBarcode;
    private Button btnBack;
    private Button btnModify;
    private MenuBean selectedMenuBean;
    private MenuBean selectedSubMenuBean;
    private LabelSurveyViewModel viewModel;
    private TextView txtLastEntryBarcode;
    private TextView txtLastEntryPrice;
    private LabelSurveyRepository labelSurveyRepository;
    private LabelSurveyRepository.LabelSurveyRepositoryListener labelSurveyRepositoryListener;
    private View.OnClickListener clickListener;

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

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

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

        initViews();
        handleKeyboard();

        populateViewModel();

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

    }

    private void getData(boolean isSwipeRefreshing) {
        swipeView.setRefreshing(isSwipeRefreshing);
        labelSurveyRepository.getAllUnsentLabelSurveys(labelSurveyRepositoryListener);
    }


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

    private void initViews() {

        etxtPrice = findViewById(R.id.etxt_label_survey_shelf_price);
        etxtSection = findViewById(R.id.etxt_label_survey_section);
        etxtBarcode = findViewById(R.id.etxt_label_survey_barcode);

        txtLastEntryBarcode = findViewById(R.id.txt_label_survey_last_entry_barcode);
        txtLastEntryPrice = findViewById(R.id.txt_label_survey_last_entry_price);

        btnBack = findViewById(R.id.btn_label_survey_back);
        btnModify = findViewById(R.id.btn_label_survey_modify);

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

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

        labelSurveyRepository = LabelSurveyRepository.getInstance();

        labelSurveyRepositoryListener = new LabelSurveyRepository.LabelSurveyRepositoryListener() {
            @Override
            public void onAddCompleted(LabelSurveyBean labelSurveyBean) {
                viewModel.getLabelSurveyList().add(labelSurveyBean);
                onSaveCompleted();
            }

            @Override
            public void onDeleteCompleted(LabelSurveyBean labelSurveyBean) {
                int index = viewModel.indexOf(labelSurveyBean);
                if (index != -1)
                    viewModel.getLabelSurveyList().remove(index);
                onSaveCompleted();
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {

            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onUpdateCompleted(LabelSurveyBean labelSurveyBean) {
                int index = viewModel.indexOf(labelSurveyBean);
                if (index != -1) {
                    viewModel.getLabelSurveyList().set(index, labelSurveyBean);
                    onSaveCompleted();
                }
            }

            @Override
            public void onLabelSurveyBeanLoaded(LabelSurveyBean labelSurveyBean) {

            }

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

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<LabelSurveyBean> labelSurveyList) {
                viewModel.setLabelSurveyList(labelSurveyList);
                populateViewModel();
                etxtSection.requestFocus();
                etxtSection.performClick();
                swipeView.setRefreshing(false);
                setProgressScreenVisibility(false, false);
            }

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

            }

            @Override
            public void onFailed() {

            }
        };


        etxtBarcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onTouch: etxtBarcode isEnabled : " + v.isEnabled());

                etxtBarcode.setEnabled(true);
                etxtBarcode.setTextIsSelectable(true);
                etxtBarcode.setFocusable(true);
                etxtBarcode.setFocusableInTouchMode(true);

                if (v.isEnabled() && !v.hasFocus()) {
                    v.requestFocus();
                }
                Log.i(TAG, "onTouch: etxtBarcode Request Focus Response : " + v.requestFocus());
            }
        });

        etxtPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.i(TAG, "onFocusChange: QUANTITY FOCUS : " + hasFocus);
                if (hasFocus) {
                    etxtPrice.setText("");
                } /*else {
                    etxtPrice.setText("0");
                }*/
            }
        });
        etxtPrice.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 (etxtPrice.getText().toString().length() > 0) {
                    float value = Float.parseFloat(etxtPrice.getText().toString());
                    if (value > 99999999.999) {
                        etxtPrice.setText(R.string.sample_max_price);
                    } else if (value < 0) {
                        etxtPrice.setText("0");
                    }

                    Log.i(TAG, "afterTextChanged: Formatted Price : " + BarcodeUtil.getFormattedPrice(value));
                }
            }

        });

        etxtSection.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_GO ||
                        actionId == EditorInfo.IME_ACTION_NEXT ||
                        actionId == EditorInfo.IME_ACTION_DONE ||
                        event != null && event.getAction() == KeyEvent.ACTION_DOWN &&
                                event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    if (event == null || !event.isShiftPressed()) {

                        if (!etxtSection.getText().toString().equals("")) {
                            viewModel.setSection(etxtSection.getText().toString());
                            populateViewModel();
                        }

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

        etxtBarcode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_GO ||
                        actionId == EditorInfo.IME_ACTION_NEXT ||
                        actionId == EditorInfo.IME_ACTION_DONE ||
                        event != null && event.getAction() == KeyEvent.ACTION_DOWN &&
                                event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    if (event == null || !event.isShiftPressed()) {

                        String barcode = etxtBarcode.getText().toString();
                        etxtBarcode.setText(BarcodeUtil.getFormattedBarcode(barcode));
                        viewModel.setBarcode(barcode);
                        viewModel.setPriceEnabled(true);
                        populateViewModel();
                        etxtPrice.requestFocus();

                        return true; // consume.
                    }
                }
                return false; // pass on to other listeners.
            }
        });
        etxtPrice.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_GO ||
                        actionId == EditorInfo.IME_ACTION_NEXT ||
                        actionId == EditorInfo.IME_ACTION_DONE ||
                        event != null && event.getAction() == KeyEvent.ACTION_DOWN &&
                                event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    if (event == null || !event.isShiftPressed()) {
                        Log.i(TAG, "onEditorAction: " + etxtPrice.getText().toString());
                        if (etxtPrice.getText().toString().length() > 0) {
                            float price = Float.parseFloat(etxtPrice.getText().toString());
                            viewModel.setPrice(price);
//                            viewModel.setPriceEnabled(false);
                            if (viewModel.isDataCollected()) {
                                saveLabelSurveyBean();
                            }
                        }
                        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);
                viewModel.setPriceEnabled(true);
                populateViewModel();
                etxtPrice.requestFocus();
            }
        };
        addBarcodeUpdateListener(barcodeUpdateListener);
    }

    private void onSaveCompleted() {
        viewModel.clearLabelSurvey();
        viewModel.setLastEntry(viewModel.getLabelSurveyList().get(viewModel.lastIndex()));
        viewModel.setModifyEnabled(false);
        populateViewModel();
        etxtSection.performClick();
        etxtSection.requestFocus();
    }

    private void handleKeyboard() {

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

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

        etxtSection.setText(viewModel.getSection());
        etxtBarcode.setText(!viewModel.isModifyEnabled() ? viewModel.getBarcode() : BarcodeUtil.getFormattedBarcode(viewModel.getBarcode()));
        etxtPrice.setText(BarcodeUtil.removeTrailingZeroes(viewModel.getPrice()));

        if (!viewModel.getSection().equals("")) {
            etxtPrice.setFocusable(viewModel.isPriceEnabled());
            etxtPrice.setEnabled(viewModel.isPriceEnabled());
            enableViews(true);
        } else {
            etxtSection.setEnabled(true);
            etxtSection.setFocusable(true);
            etxtSection.setFocusableInTouchMode(true);
            etxtSection.setTextIsSelectable(true);
            enableViews(false);
        }

        if (!viewModel.getLabelSurveyList().isEmpty()) {
            viewModel.setLastEntry(viewModel.getLabelSurveyList().get(viewModel.lastIndex()));
        } else {
            viewModel.setLastEntry(null);
        }
        if (viewModel.getLastEntry() != null) {
            txtLastEntryBarcode.setText(viewModel.getLastEntry().getBarcode());
            txtLastEntryPrice.setText(BarcodeUtil.removeTrailingZeroes(viewModel.getLastEntry().getPrice()));
        } else {
            txtLastEntryBarcode.setText("");
            txtLastEntryPrice.setText("");
        }

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


    }

    private void saveLabelSurveyBean() {
        LabelSurveyBean labelSurveyBean = viewModel.generateLabelSurveyBean();

        if (viewModel.isModifyEnabled()) {
            labelSurveyBean.setId(viewModel.getModifiedID());
            labelSurveyRepository.updateLabelSurvey(labelSurveyBean, labelSurveyRepositoryListener);
        } else {
            labelSurveyRepository.insertLabelSurvey(labelSurveyBean, labelSurveyRepositoryListener);
        }
    }

    private void enableViews(boolean isEnable) {

        Log.i(TAG, "enableViews: etxtPrice : " + (viewModel.isPriceEnabled() && isEnable));
        etxtPrice.setEnabled(viewModel.isPriceEnabled() && isEnable);
        etxtBarcode.setEnabled(isEnable);

        etxtPrice.setFocusable(viewModel.isPriceEnabled() && isEnable);
        etxtBarcode.setFocusable(isEnable);

        etxtBarcode.setTextIsSelectable(isEnable);
        etxtBarcode.setFocusableInTouchMode(isEnable);
        etxtPrice.setTextIsSelectable(viewModel.isPriceEnabled() && isEnable);
        etxtPrice.setFocusableInTouchMode(viewModel.isPriceEnabled() && isEnable);

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

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

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

    public void onLabelSurveyModifyClick(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();
        }

    }

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

}
