/*
 * Copyright (C) 2022 - Florindo Smilari (spherIC)
 */
package ch.spherIC.recurvebowsight.ui.configuration;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;

import java.text.DecimalFormat;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import ch.spherIC.recurvebowsight.R;
import ch.spherIC.recurvebowsight.database.dao.RiserDao;
import ch.spherIC.recurvebowsight.databinding.ActivityRiserConfigurationBinding;
import ch.spherIC.recurvebowsight.model.IRiser;
import ch.spherIC.recurvebowsight.model.impl.Riser;
import ch.spherIC.recurvebowsight.ui.userguide.UserGuideRiserActivity;
import ch.spherIC.recurvebowsight.utilities.NoFilterArrayAdapter;
import ch.spherIC.recurvebowsight.utilities.PlatformUtils;

public class RiserConfigurationActivity extends AppCompatActivity {

    private ActivityRiserConfigurationBinding binding;
    private RiserConfigurationViewModel riserConfigurationViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_riser_configuration);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(R.string.title_activity_riser_configuration);

        this.riserConfigurationViewModel = new ViewModelProvider(this).get(RiserConfigurationViewModel.class);
        this.binding = ActivityRiserConfigurationBinding.bind(findViewById(R.id.activity_riser_configuration));

        addObservers();
        addRiserSpinnerListener();
        addButtonListeners();
        loadRisers();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        MenuItem menuItemSettings = menu.findItem(R.id.action_settings);
        MenuItem menuItemHelp = menu.findItem(R.id.action_help);
        menuItemSettings.setEnabled(false);
        menuItemHelp.setEnabled(true);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
            case R.id.action_help:
                Intent userGuideRiserIntent = new Intent(this.binding.getRoot().getContext(), UserGuideRiserActivity.class);
                startActivity(userGuideRiserIntent);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void addObservers() {
        DecimalFormat dF = new DecimalFormat("#.#");
        this.riserConfigurationViewModel.getManufacturer().observe(this, manufacturer -> this.binding.rcManufacturerTxt.setText(manufacturer));
        this.riserConfigurationViewModel.getModel().observe(this, model -> this.binding.rcModelTxt.setText(model));
        this.riserConfigurationViewModel.getSize().observe(this, size -> this.binding.rcSizeTxt.setText(size != null ? dF.format(size) : ""));
        this.riserConfigurationViewModel.getVVisH().observe(this, vVisH -> this.binding.rcVvisHTxt.setText(vVisH != null ? dF.format(vVisH) : ""));
        this.riserConfigurationViewModel.getVVisV().observe(this, vVisV -> this.binding.rcVvisVTxt.setText(vVisV != null ? dF.format(vVisV) : ""));
    }

    private void addRiserSpinnerListener() {
        AutoCompleteTextView textView = findViewById(R.id.riserSelectionTxt);
        textView.setOnItemClickListener((parent, view, position, id) -> {
            IRiser selectedRiser = (IRiser) textView.getAdapter().getItem(position);
            if (selectedRiser != null) {
                riserConfigurationViewModel.setRiser(selectedRiser);
            }
        });
    }

    private void addButtonListeners() {
        Button newButton = findViewById(R.id.risercfg_button_new);
        newButton.setOnClickListener(v -> addNewRiser());

        Button deleteButton = findViewById(R.id.risercfg_button_delete);
        deleteButton.setOnClickListener(v -> deleteRiser());

        Button saveButton = findViewById(R.id.risercfg_button_save);
        saveButton.setOnClickListener(v -> saveRiserConfiguration());
    }


    private void loadRisers() {
        List<IRiser> risers = RiserDao.getInstance().loadAll();
        ArrayAdapter<IRiser> adapter = new NoFilterArrayAdapter<IRiser>(this, android.R.layout.simple_dropdown_item_1line, risers);
        AutoCompleteTextView textView = binding.riserSelectionTxt;
        textView.setAdapter(adapter);
        textView.invalidate();
    }

    private void addNewRiser() {
        IRiser newRiser = new Riser(0, "", "", null, null, null);
        this.riserConfigurationViewModel.setRiser(newRiser);
        String strMandatory = getString(R.string.caption_mandatory);
        this.binding.riserSelectionTxt.setText(null, false);
        this.binding.rcManufacturerTxt.setError(strMandatory);
        this.binding.rcModelTxt.setError(strMandatory);
        this.binding.rcSizeTxt.setError(strMandatory);
        this.binding.rcVvisHTxt.setError(strMandatory);
        this.binding.rcVvisVTxt.setError(strMandatory);
        AutoCompleteTextView textView = binding.riserSelectionTxt;
        ((ArrayAdapter<IRiser>) textView.getAdapter()).insert(newRiser, 0);
        textView.setAdapter((ArrayAdapter<IRiser>) textView.getAdapter());
        textView.setSelection(0);
    }

    private void saveRiserConfiguration() {
        if (!validateInputs()) {
            return;
        }
        this.riserConfigurationViewModel.setManufacturerText(this.binding.rcManufacturerTxt.getText().toString());
        this.riserConfigurationViewModel.setModelText(this.binding.rcModelTxt.getText().toString());
        this.riserConfigurationViewModel.setSize(PlatformUtils.parseDouble(this.binding.rcSizeTxt.getText().toString()));
        this.riserConfigurationViewModel.setVVisH(PlatformUtils.parseDouble(this.binding.rcVvisHTxt.getText().toString()));
        this.riserConfigurationViewModel.setVVisV(PlatformUtils.parseDouble(this.binding.rcVvisVTxt.getText().toString()));

        IRiser lRiser = this.riserConfigurationViewModel.getRiser().getValue();
        if (lRiser.getId() > 0) {
            RiserDao.getInstance().update(lRiser);
            PlatformUtils.toast(RiserConfigurationActivity.this, String.format(getString(R.string.caption_Cfg_UpdateSuccessful), lRiser)).show();
        } else {
            lRiser = RiserDao.getInstance().insert(lRiser);
            loadRisers();
            AutoCompleteTextView textView = this.binding.riserSelectionTxt;
            final int position = ((ArrayAdapter<IRiser>) textView.getAdapter()).getPosition(lRiser);
            textView.setListSelection(position);
            textView.setText(lRiser.toString(), false);
            ((ArrayAdapter<IRiser>) textView.getAdapter()).getFilter().filter(null);
            PlatformUtils.toast(RiserConfigurationActivity.this, String.format(getString(R.string.caption_Cfg_SaveSuccessful), lRiser)).show();
        }
    }

    private boolean validateInputs() {
        int invalidFields = 0;
        if (this.binding.rcManufacturerTxt.getText().toString().isEmpty() || this.binding.rcManufacturerTxt.getText().toString().equals("*")) {
            invalidFields++;
        }
        if (this.binding.rcModelTxt.getText().toString().isEmpty() || this.binding.rcModelTxt.getText().toString().equals("*")) {
            invalidFields++;
        }
        if (this.binding.rcSizeTxt.getText() == null || this.binding.rcSizeTxt.getText().toString().equals("")) {
            invalidFields++;
        }
        if (this.binding.rcVvisHTxt.getText() == null || this.binding.rcVvisHTxt.getText().toString().equals("")) {
            invalidFields++;
        }
        if (this.binding.rcVvisVTxt.getText() == null || this.binding.rcVvisVTxt.getText().toString().equals("")) {
            invalidFields++;
        }
        if (invalidFields > 0) {
            PlatformUtils.toast(this, getResources().getString(R.string.caption_Cfg_FillAllMandatoryFields)).show();
            return false;
        }
        return true;
    }

    private void deleteRiser() {
        IRiser lRiser = this.riserConfigurationViewModel.getRiser().getValue();

        if (lRiser != null) {
            AlertDialog dlg = PlatformUtils.getDeleteConfirmDialog(this, lRiser.toString(), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    String message = String.format(getString(R.string.caption_Cfg_DeleteSuccessful), lRiser);
                    try {
                        RiserDao.getInstance().delete(lRiser);
                        loadRisers();
                        riserConfigurationViewModel.setRiser(null);
                        binding.riserSelectionTxt.setText(null, false);
                    } catch (Exception e) {
                        message = getString(R.string.caption_Cfg_DeleteNotPossible);
                    }
                    PlatformUtils.toast(RiserConfigurationActivity.this, message).show();
                }
            });
            dlg.show();
        }
    }
}