package in.techware.carrefour.activity.it;

import android.arch.lifecycle.ViewModelProviders;
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.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
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.WasteRepository;
import in.techware.carrefour.dialogs.ConfirmationDialog;
import in.techware.carrefour.dialogs.SelectDialog;
import in.techware.carrefour.listeners.BarcodeUpdateListener;
import in.techware.carrefour.model.MenuBean;
import in.techware.carrefour.model.WasteBean;
import in.techware.carrefour.util.AppConstants;
import in.techware.carrefour.util.BarcodeUtil;
import in.techware.carrefour.util.menuUtils.DropDownMenuUtil;
import in.techware.carrefour.viewModels.WasteViewModel;

public class WasteActivity extends BaseAppCompatNoDrawerActivity {

    private static final String TAG = "WasteA";
    private CheckBox cbQuantity;
    private EditText etxtQuantity;
    private EditText etxtOriginType;
    private EditText etxtBarcode;
    private Button btnChange;
    private Button btnBack;
    private Button btnModify;
    private Button btnDelete;
    private Spinner spinner;
    private MenuBean selectedMenuBean;
    private MenuBean selectedSubMenuBean;
    private WasteViewModel viewModel;
    private TextView txtLastEntryBarcode;
    private TextView txtLastEntryQuantity;
    private LinearLayout llOrigin;
    private TextView txtOrigin;
    private WasteRepository wasteRepository;
    private WasteRepository.WasteRepositoryListener wasteRepositoryListener;

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

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

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

        initViews();
//        handleKeyboard();

        populateViewModel();

        if (getSupportActionBar() != null) {
            setTitle(R.string.title_waste, 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.getWasteList().isEmpty()) {
            setProgressScreenVisibility(true, true);
            getData(false);
            viewModel.setOriginTypeList(DropDownMenuUtil.getOriginList());
        } else {
            getData(true);
        }

    }

    private void getData(boolean isSwipeRefreshing) {
        swipeView.setRefreshing(isSwipeRefreshing);
        wasteRepository.getAllUnsentWastes(wasteRepositoryListener);
    }


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

    private void initViews() {

        spinner = findViewById(R.id.spinner_waster_origin);
        llOrigin = findViewById(R.id.ll_waste_origin);
        txtOrigin = findViewById(R.id.txt_waste_origin);
        cbQuantity = findViewById(R.id.cb_waste_quantity);
        etxtQuantity = findViewById(R.id.etxt_waste_quantity);
        etxtOriginType = findViewById(R.id.etxt_waste_type);
        etxtBarcode = findViewById(R.id.etxt_waste_barcode);

        txtLastEntryBarcode = findViewById(R.id.txt_waste_last_entry_barcode);
        txtLastEntryQuantity = findViewById(R.id.txt_waste_last_entry_quantity);

        btnChange = findViewById(R.id.btn_waste_change);
        btnBack = findViewById(R.id.btn_waste_back);
        btnModify = findViewById(R.id.btn_waste_modify);
        btnDelete = findViewById(R.id.btn_waste_delete);

        llOrigin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onWasteOriginClick(v);
            }
        });
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onWasteBackClick(v);
            }
        });
        btnChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onWasteChangeClick(v);
            }
        });
        btnModify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onWasteModifyClick(v);
            }
        });
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onWasteDeleteClick(v);
            }
        });


        wasteRepository = WasteRepository.getInstance();

        wasteRepositoryListener = new WasteRepository.WasteRepositoryListener() {
            @Override
            public void onAddCompleted(WasteBean wasteBean) {
                viewModel.getWasteList().add(wasteBean);
                viewModel.clearWaste();
                viewModel.setLastEntry(wasteBean);
                viewModel.setModifyEnabled(false);
                populateViewModel();
            }

            @Override
            public void onDeleteCompleted(WasteBean wasteBean) {
                int index = viewModel.indexOf(wasteBean);
                if (index != -1)
                    viewModel.getWasteList().remove(index);
                populateViewModel();
            }

            @Override
            public void onDeleteAllCompleted() {

            }

            @Override
            public void onDeleteAllSentCompleted() {

            }

            @Override
            public void onDeleteAllUnsentCompleted() {

            }

            @Override
            public void onUpdateCompleted(WasteBean wasteBean) {
                int index = viewModel.indexOf(wasteBean);
                if (index != -1) {
                    viewModel.getWasteList().set(index, wasteBean);
                    viewModel.clearWaste();
                    viewModel.setLastEntry(viewModel.getWasteList().get(viewModel.lastIndex()));
                    viewModel.setModifyEnabled(false);
                    populateViewModel();
                    etxtBarcode.requestFocus();
                }
            }

            @Override
            public void onWasteBeanLoaded(WasteBean wasteBean) {

            }

            @Override
            public void onAllListLoaded(ArrayList<WasteBean> wasteListBean) {

            }

            @Override
            public void onAllUnsentListLoaded(ArrayList<WasteBean> wasteList) {
                viewModel.setWasteList(wasteList);
                populateViewModel();
                swipeView.setRefreshing(false);
                setProgressScreenVisibility(false, false);
            }

            @Override
            public void onAllSentListLoaded(ArrayList<WasteBean> wasteListBean) {

            }

            @Override
            public void onFailed() {

            }
        };

        /*List<String> origins = Arrays.asList(getResources().getStringArray(R.array.spinner_waste_type));
        viewModel.setOriginTypeList(origins);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, origins);

        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                Toast.makeText(WasteActivity.this, "ITEM SELECTED", Toast.LENGTH_SHORT).show();
                spinner.setEnabled(false);
                spinner.setFocusable(false);
                String str = "";
                if (position == 0) {
                    str = "W1";
                } else if (position == 1) {
                    str = "W3";
                } else {
                    str = "W5";
                }
                etxtOriginType.setText(str);
                viewModel.setOriginType(viewModel.getOriginTypeList().get(position));
                viewModel.setOriginTypeSelectedPosition(position);
                viewModel.setOriginTypeCode(str);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                spinner.setEnabled(false);
                spinner.setFocusable(false);
            }

        });
*/
        /*etxtOriginType.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()) {

                        // TODO: 22-07-2018 Change Waste Type based on the input

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

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

        etxtBarcode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.i(TAG, "onFocusChange: etxtBarcode : " + hasFocus);
            }
        });
        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");
                }*/
            }
        });
        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));
                }
            }

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

                                        @Override
                                        public void onNoClicked() {
                                            viewModel.setQuantity(1);
                                            //                                            viewModel.setQuantityEnabled(false);
                                            if (viewModel.isDataCollected()) {
                                                saveWasteBean();
                                            }
                                        }
                                    });
                            confirmationDialog.show(R.string.message_quantity_is_greater_than_10);
                        } else {
                            viewModel.setQuantity(quantity);
                            //                            viewModel.setQuantityEnabled(false);
                            if (viewModel.isDataCollected()) {
                                saveWasteBean();
                            }
                        }
                    }
                    return true; // consume.
                }
                return false; // pass on to other listeners.
            }
        });
        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()) {
                        saveWasteBean();
                    } else if (viewModel.isQuantityEnabled()) {
                        etxtQuantity.requestFocus();
                    }

                    return true; // consume.

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

        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()) {
                    saveWasteBean();
                } else if (viewModel.isQuantityEnabled()) {
                    etxtQuantity.requestFocus();
                }
            }
        };
        addBarcodeUpdateListener(barcodeUpdateListener);
    }

    private void handleKeyboard() {
        if (getSharedPreferences(AppConstants.PREF_FILE, 0).getBoolean(AppConstants.KEYBOARD_STATUS, false)) {
            etxtBarcode.setFocusableInTouchMode(true);
            etxtOriginType.setFocusableInTouchMode(true);
            etxtQuantity.setFocusableInTouchMode(true);
        }
    }

    private void populateViewModel() {

        Log.i(TAG, "populateViewModel: VIEW MODEL : " + new Gson().toJson(viewModel));

        etxtOriginType.setText(viewModel.getOriginTypeCode());
        etxtBarcode.setText(!viewModel.isModifyEnabled() ? viewModel.getBarcode() : BarcodeUtil.getFormattedBarcode(viewModel.getBarcode()));
        etxtQuantity.setText(!viewModel.isModifyEnabled() ? "" : BarcodeUtil.removeTrailingZeroes(viewModel.getQuantity()));
//        etxtQuantity.setText(String.valueOf(viewModel.getQuantity()));
        cbQuantity.setChecked(viewModel.isQuantityEnabled());

        if (viewModel.getOriginTypeSelectedPosition() != -1) {
            spinner.setSelection(viewModel.getOriginTypeSelectedPosition());
            txtOrigin.setText(viewModel.getOriginType());
            etxtQuantity.setFocusable(viewModel.isQuantityEnabled());
            etxtQuantity.setEnabled(viewModel.isQuantityEnabled());
            enableViews(true);
        } else {
            enableViews(false);
        }

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


    }

    private void saveWasteBean() {
        WasteBean wasteBean = viewModel.generateWasteBean();

        if (viewModel.isModifyEnabled()) {
            wasteBean.setId(viewModel.getLastEntry().getId());
            wasteRepository.updateWaste(wasteBean, wasteRepositoryListener);
        } else {
            wasteRepository.insertWaste(wasteBean, wasteRepositoryListener);
        }
    }

    private void enableViews(boolean isEnable) {
        spinner.setSelected(isEnable);

        llOrigin.setEnabled(!isEnable);
        spinner.setEnabled(!isEnable);
        Log.i(TAG, "enableViews: etxtQuantity : " + (viewModel.isQuantityEnabled() && isEnable));
        etxtQuantity.setEnabled(viewModel.isQuantityEnabled() && isEnable);
        etxtBarcode.setEnabled(isEnable);
        cbQuantity.setEnabled(isEnable);

        llOrigin.setFocusable(!isEnable);
        spinner.setFocusable(!isEnable);
        etxtQuantity.setFocusable(viewModel.isQuantityEnabled() && isEnable);
        etxtBarcode.setFocusable(isEnable);
        cbQuantity.setFocusable(isEnable);

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

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

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

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

                llOrigin.setEnabled(false);
                llOrigin.setFocusable(false);
                txtOrigin.setText(value);
                etxtOriginType.setText(viewModel.getOriginTypeList().get(position).getOriginCode());
                viewModel.setOriginType(viewModel.getOriginTypeList().get(position).getOriginName());
                viewModel.setOriginTypeSelectedPosition(position);
                viewModel.setOriginTypeCode(viewModel.getOriginTypeList().get(position).getOriginCode());
                populateViewModel();
            }

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

    }

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

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

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

        if (!viewModel.getWasteList().isEmpty() && viewModel.getLastEntry() != null) {
            wasteRepository.deleteWaste(viewModel.getLastEntry(), wasteRepositoryListener);
        }

    }

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

        spinner.setEnabled(true);
        spinner.setFocusable(true);
        llOrigin.setEnabled(true);
        llOrigin.setFocusable(true);
    }

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