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.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
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.dbUtils.repositories.PromotionRepository;
import in.techware.carrefour.dialogs.SelectDialog;
import in.techware.carrefour.listeners.BarcodeUpdateListener;
import in.techware.carrefour.model.MenuBean;
import in.techware.carrefour.model.PromotionBean;
import in.techware.carrefour.util.AppConstants;
import in.techware.carrefour.util.BarcodeUtil;
import in.techware.carrefour.util.menuUtils.DropDownMenuUtil;
import in.techware.carrefour.viewModels.PromotionViewModel;

public class PromotionActivity extends BaseAppCompatNoDrawerActivity {

    private static final String TAG = "PromotionA";
    private Button btnBack;
    private Button btnModify;
    private MenuBean selectedMenuBean;
    private MenuBean selectedSubMenuBean;
    private PromotionViewModel viewModel;
    private TextView txtLastEntryBarcode;
    private LinearLayout llGondola;
    private TextView txtGondola;
    private EditText etxtBarcode;
    private PromotionRepository promotionRepository;
    private PromotionRepository.PromotionRepositoryListener promotionRepositoryListener;
    private View.OnClickListener clickListener;


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

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

        initViews();
        handleKeyboard();

        populateViewModel();

        if (getSupportActionBar() != null) {
            setTitle(R.string.title_promotion, 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.getPromotionList().isEmpty()) {
            setProgressScreenVisibility(true, true);
            getData(false);
            viewModel.setGondolaList(DropDownMenuUtil.getGondolaList());
        } else {
            getData(true);
        }

    }

    private void getData(boolean isSwipeRefreshing) {
        swipeView.setRefreshing(isSwipeRefreshing);
        PromotionRepository.getInstance().getAllUnsentPromotions(promotionRepositoryListener);
    }


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

    private void initViews() {

        llGondola = findViewById(R.id.ll_promotion_gondola);
        txtGondola = findViewById(R.id.txt_promotion_gondola);
        etxtBarcode = findViewById(R.id.etxt_promotion_barcode);

        txtLastEntryBarcode = findViewById(R.id.txt_promotion_last_entry_barcode);

        btnBack = findViewById(R.id.btn_promotion_back);
        btnModify = findViewById(R.id.btn_promotion_modify);

        llGondola.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPromotionGondolaClick(v);
            }
        });
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPromotionBackClick(v);
            }
        });
        btnModify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPromotionModifyClick(v);
            }
        });

        promotionRepository = PromotionRepository.getInstance();

        promotionRepositoryListener = new PromotionRepository.PromotionRepositoryListener() {
            @Override
            public void onAddCompleted(PromotionBean promotionBean) {
                viewModel.getPromotionList().add(promotionBean);
                onSaveCompleted();
            }

            @Override
            public void onDeleteCompleted(PromotionBean promotionBean) {
                int index = viewModel.indexOf(promotionBean);
                if (index != -1)
                    viewModel.getPromotionList().remove(index);
                populateViewModel();
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {

            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onUpdateCompleted(PromotionBean promotionBean) {
                int index = viewModel.indexOf(promotionBean);
                if (index != -1) {
                    viewModel.getPromotionList().set(index, promotionBean);
                    onSaveCompleted();
                }
            }

            @Override
            public void onPromotionBeanLoaded(PromotionBean promotionBean) {

            }

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

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<PromotionBean> promotionList) {
                viewModel.setPromotionList(promotionList);
                populateViewModel();
                swipeView.setRefreshing(false);
                setProgressScreenVisibility(false, false);
            }

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

            }

            @Override
            public void onFailed() {

            }
        };

        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()) {
                        savePromotionBean();
                    }

                    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);
                if (viewModel.isDataCollected()) {
                    savePromotionBean();
                }
            }
        };
        addBarcodeUpdateListener(barcodeUpdateListener);
    }

    private void onSaveCompleted() {
        viewModel.clearPromotion();
        viewModel.setLastEntry(viewModel.getPromotionList().get(viewModel.lastIndex()));
        viewModel.setModifyEnabled(false);
        populateViewModel();
        etxtBarcode.requestFocus();
    }

    private void handleKeyboard() {
        if (getSharedPreferences(AppConstants.PREF_FILE, 0).getBoolean(AppConstants.KEYBOARD_STATUS, false)) {
            etxtBarcode.setFocusableInTouchMode(true);
        } else {
//            etxtZoneType.setOnFocusChangeListener(focusChangedListener);
//            etxtBarcode.setOnFocusChangeListener(focusChangedListener);
//            etxtQuantity.setOnFocusChangeListener(focusChangedListener);
            etxtBarcode.setFocusableInTouchMode(false);
            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()));
        txtGondola.setText(viewModel.getGondola());

        if (viewModel.getGondolaSelectedPosition() != -1) {
            txtGondola.setText(viewModel.getGondola());
            enableViews(true);
        } else {
            enableViews(false);
        }

        if (!viewModel.getPromotionList().isEmpty()) {
            viewModel.setLastEntry(viewModel.getPromotionList().get(viewModel.lastIndex()));
        } else {
            viewModel.setLastEntry(null);
        }

        if (viewModel.getLastEntry() != null) {
            txtLastEntryBarcode.setText(viewModel.getLastEntry().getBarcode());
        } else {
            txtLastEntryBarcode.setText("");
        }

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


    }

    private void savePromotionBean() {
        PromotionBean promotionBean = viewModel.generatePromotionBean();

        if (viewModel.isModifyEnabled()) {
            promotionBean.setId(viewModel.getLastEntry().getId());
            promotionRepository.updatePromotion(promotionBean, promotionRepositoryListener);
        } else {
            promotionRepository.insertPromotion(promotionBean, promotionRepositoryListener);
        }
    }

    private void enableViews(boolean isEnable) {

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

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

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

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

                txtGondola.setText(value);
                viewModel.setGondola(viewModel.getGondolaList().get(position));
                viewModel.setGondolaSelectedPosition(position);
                populateViewModel();
            }

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

    }

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

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

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

        if (!viewModel.getPromotionList().isEmpty() && viewModel.getLastEntry() != null) {
            promotionRepository.deletePromotion(
                    viewModel.getLastEntry()
                    , promotionRepositoryListener);
        }

    }

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