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.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.OutOfStockRepository;
import in.techware.carrefour.listeners.BarcodeUpdateListener;
import in.techware.carrefour.model.MenuBean;
import in.techware.carrefour.model.OutOfStockBean;
import in.techware.carrefour.util.AppConstants;
import in.techware.carrefour.util.BarcodeUtil;
import in.techware.carrefour.viewModels.OutOfStockViewModel;

public class OutOfStockActivity extends BaseAppCompatNoDrawerActivity {

    private static final String TAG = "OutOfStockA";
    private Button btnBack;
    private Button btnModify;
    private MenuBean selectedMenuBean;
    private MenuBean selectedSubMenuBean;
    private OutOfStockViewModel viewModel;
    private TextView txtLastEntryBarcode;
    private EditText etxtBarcode;
    private OutOfStockRepository outOfStockRepository;
    private OutOfStockRepository.OutOfStockRepositoryListener outOfStockRepositoryListener;
    private View.OnClickListener clickListener;

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

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

        initViews();
        handleKeyboard();

        populateViewModel();

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

    }

    private void getData(boolean isSwipeRefreshing) {
        swipeView.setRefreshing(isSwipeRefreshing);
        OutOfStockRepository.getInstance().getAllUnsentOutOfStocks(outOfStockRepositoryListener);
    }


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

    private void initViews() {

        etxtBarcode = findViewById(R.id.etxt_out_of_stock_barcode);

        txtLastEntryBarcode = findViewById(R.id.txt_out_of_stock_last_entry_barcode);

        btnBack = findViewById(R.id.btn_out_of_stock_back);
        btnModify = findViewById(R.id.btn_out_of_stock_modify);

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

        outOfStockRepository = OutOfStockRepository.getInstance();

        outOfStockRepositoryListener = new OutOfStockRepository.OutOfStockRepositoryListener() {
            @Override
            public void onAddCompleted(OutOfStockBean outOfStockBean) {
                viewModel.getOutOfStockList().add(outOfStockBean);
                onSaveCompleted();
            }

            @Override
            public void onDeleteCompleted(OutOfStockBean outOfStockBean) {
                int index = viewModel.indexOf(outOfStockBean);
                if (index != -1)
                    viewModel.getOutOfStockList().remove(index);
                populateViewModel();
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {

            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onUpdateCompleted(OutOfStockBean outOfStockBean) {
                int index = viewModel.indexOf(outOfStockBean);
                if (index != -1) {
                    viewModel.getOutOfStockList().set(index, outOfStockBean);
                    onSaveCompleted();
                }
            }

            @Override
            public void onOutOfStockBeanLoaded(OutOfStockBean outOfStockBean) {

            }

            @Override
            public void onAllListLoaded(ArrayList<OutOfStockBean> outOfStockListBean) {

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<OutOfStockBean> outOfStockList) {
                viewModel.setOutOfStockList(outOfStockList);
                populateViewModel();
                swipeView.setRefreshing(false);
                setProgressScreenVisibility(false, false);
            }

            @Override
            public void onAllSentListLoaded(ArrayList<OutOfStockBean> outOfStockListBean) {

            }

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

                    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()) {
                    saveOutOfStockBean();
                }
            }
        };
        addBarcodeUpdateListener(barcodeUpdateListener);
    }

    private void onSaveCompleted() {
        viewModel.clearOutOfStock();
        viewModel.setLastEntry(viewModel.getOutOfStockList().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()));

        enableViews(true);

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

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

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


    }

    private void saveOutOfStockBean() {
        OutOfStockBean outOfStockBean = viewModel.generateOutOfStockBean();

        if (viewModel.isModifyEnabled()) {
            outOfStockBean.setBarcode(viewModel.getLastEntry().getBarcode());
            outOfStockRepository.updateOutOfStock(outOfStockBean, outOfStockRepositoryListener);
        } else {
            outOfStockRepository.insertOutOfStock(outOfStockBean, outOfStockRepositoryListener);
        }
    }

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

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

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

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

    }

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

        if (!viewModel.getOutOfStockList().isEmpty() && viewModel.getLastEntry() != null) {
            outOfStockRepository.deleteOutOfStock(
                    viewModel.getLastEntry()
                    , outOfStockRepositoryListener);
        }

    }

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

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