package ch.spherIC.recurvebowsight.configuration;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;

import android.content.DialogInterface;

import android.content.pm.ActivityInfo;

import android.os.Bundle;

import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.view.View.OnClickListener;

import android.widget.AdapterView;

import android.widget.AdapterView.OnItemSelectedListener;

import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import ch.spherIC.recurvebowsight.DialogFactory;
import ch.spherIC.recurvebowsight.R;
import ch.spherIC.recurvebowsight.RBSMainActivity;
import ch.spherIC.recurvebowsight.components.FontArrayAdapter;
import ch.spherIC.recurvebowsight.components.RiserSpinner;
import ch.spherIC.recurvebowsight.components.SightSpinner;
import ch.spherIC.recurvebowsight.components.XSpinner;
import ch.spherIC.recurvebowsight.database.dao.ArcherySetupDao;
import ch.spherIC.recurvebowsight.database.dao.RiserDao;
import ch.spherIC.recurvebowsight.database.dao.SightDao;
import ch.spherIC.recurvebowsight.model.ArcherySetup;
import ch.spherIC.recurvebowsight.model.IArcherySetup;
import ch.spherIC.recurvebowsight.model.IRiser;
import ch.spherIC.recurvebowsight.model.ISight;
import ch.spherIC.recurvebowsight.utilities.CompatibilityUtil;
import ch.spherIC.recurvebowsight.utilities.PlatformUtils;

import java.text.DecimalFormat;

import java.util.List;


public class ArcherySetupConfigurationActivity extends Activity {

    public static final DecimalFormat DF = new DecimalFormat("0.###");

    private XSpinner asArcherySetupSpinner;
    private TextView asLabelTxtFld;
    private SightSpinner asSightSpinner;
    private RiserSpinner asRiserSpinner;
    private TextView asArrowDiameterTxtFld;
    private TextView asArrowCwTxtFld;
    private TextView asArrowWeightTxtFld;
    private TextView asArrowV0TxtFld;
    private TextView asArrowCenterHeightTxtFld;
    private TextView asBowPulloutTxtFld;
    private TextView asArrowNockHeightTxtFld;
    private TextView ashNATxtFld;
    private TextView asNockRaisingTxtFld;
    private TextView asBraceHeightTxtFld;
    private TextView asDeltaTimeTxtFld;
    private TextView asCalcPrecisionTxtFld;
    private TextView asSightVertScaleMiddleTxtFld;
    private TextView asSightHorzSettingTxtFld;


    private Button newBtn;
    private Button saveBtn;
    private Button deleteBtn;

    private IArcherySetup selectedArcherySetup;


    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_archery_setup_configuration);
        if (CompatibilityUtil.isTablet(getApplicationContext())) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        initializeComponents();
        addArcherySetupSpinnerListener();
        addButtonListeners();
        loadSpinners();
        loadArcherySetupSpinner();
    }

    private void loadSpinners() {

        List<ISight> sights = SightDao.getInstance().loadAll();
        List<IRiser> risers = RiserDao.getInstance().loadAll();

        this.asSightSpinner.setAdapter(new FontArrayAdapter<ISight>(this, R.layout.rbs_spinner, sights, this.asSightSpinner));
        this.asRiserSpinner.setAdapter(new FontArrayAdapter<IRiser>(this, R.layout.rbs_spinner, risers, this.asRiserSpinner));
    }

    private void loadArcherySetupSpinner() {

        List<IArcherySetup> archerySetups = ArcherySetupDao.getInstance().loadAll();
        this.asArcherySetupSpinner.setAdapter(new FontArrayAdapter<IArcherySetup>(this, R.layout.rbs_spinner, archerySetups,
                                                                                  this.asArcherySetupSpinner));
    }

    private void initializeComponents() {
        this.asArcherySetupSpinner = (XSpinner) findViewById(R.id.asArcherySetupSpinner);
        this.asLabelTxtFld = (TextView) findViewById(R.id.asLabelTxtFld);
        this.asSightSpinner = (SightSpinner) findViewById(R.id.asSightSpinner);
        this.asRiserSpinner = (RiserSpinner) findViewById(R.id.asRiserSpinner);
        this.asArrowDiameterTxtFld = (TextView) findViewById(R.id.asArrowDiameterTxtFld);
        this.asArrowCwTxtFld = (TextView) findViewById(R.id.asArrowCwTxtFld);
        this.asArrowWeightTxtFld = (TextView) findViewById(R.id.asArrowWeigthTxtFld);
        this.asArrowV0TxtFld = (TextView) findViewById(R.id.asArrowV0TxtFld);
        this.asArrowCenterHeightTxtFld = (TextView) findViewById(R.id.asTargetHeigthTxtFld);
        this.asBowPulloutTxtFld = (TextView) findViewById(R.id.asBowPulloutTxtFld);
        this.asArrowNockHeightTxtFld = (TextView) findViewById(R.id.asNockHeightTxtFld);
        this.ashNATxtFld = (TextView) findViewById(R.id.ashNATxtFld);
        this.asNockRaisingTxtFld = (TextView) findViewById(R.id.asNockRaisingTxtFld);
        this.asBraceHeightTxtFld = (TextView) findViewById(R.id.asBraceHeightTxtFld);
        this.asDeltaTimeTxtFld = (TextView) findViewById(R.id.asDeltaTimeTxtFld);
        this.asCalcPrecisionTxtFld = (TextView) findViewById(R.id.asCalcPrecisionTxtFld);
        this.asSightVertScaleMiddleTxtFld = (TextView) findViewById(R.id.asSightVertScaleMiddleTxtFld);
        this.asSightHorzSettingTxtFld = (TextView) findViewById(R.id.asSightHorzSettingTxtFld);

        this.newBtn = (Button) findViewById(R.id.rcBtnNew);
        this.saveBtn = (Button) findViewById(R.id.rcBtnSave);
        this.deleteBtn = (Button) findViewById(R.id.rcBtnDelete);
    }

    private void addArcherySetupSpinnerListener() {

        this.asArcherySetupSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                @Override
                public void onItemSelected(final AdapterView<?> parent, final View view, final int position,
                                           final long id) {
                    IArcherySetup as = (IArcherySetup) ArcherySetupConfigurationActivity.this.asArcherySetupSpinner.getSelectedItem();

                    ArcherySetupConfigurationActivity.this.asLabelTxtFld.setText(as.getName());
                    if (as.getSight() == null) {
                        ArcherySetupConfigurationActivity.this.asSightSpinner.setSelection(0);
                    } else {
                        ArcherySetupConfigurationActivity.this.asSightSpinner.setSelectedSight(as.getSight());
                    }
                    if (as.getRiser() == null) {
                        ArcherySetupConfigurationActivity.this.asRiserSpinner.setSelection(0);
                    } else {
                        ArcherySetupConfigurationActivity.this.asRiserSpinner.setSelectedRiser(as.getRiser());
                    }
                    ArcherySetupConfigurationActivity.this.asArrowDiameterTxtFld.setText(DF.format(as.getArrowDiameter()));
                    ArcherySetupConfigurationActivity.this.asArrowCwTxtFld.setText(DF.format(as.getArrowCw()));
                    ArcherySetupConfigurationActivity.this.asArrowWeightTxtFld.setText(DF.format(as.getArrowWeight()));
                    ArcherySetupConfigurationActivity.this.asArrowV0TxtFld.setText(DF.format(as.getArrowV0()));
                    ArcherySetupConfigurationActivity.this.asArrowCenterHeightTxtFld.setText(DF.format(as.getArrowCenterHeight()));
                    ArcherySetupConfigurationActivity.this.asBowPulloutTxtFld.setText(DF.format(as.getBowPullout()));
                    ArcherySetupConfigurationActivity.this.asArrowNockHeightTxtFld.setText(DF.format(as.getArrowNockHeight()));
                    ArcherySetupConfigurationActivity.this.ashNATxtFld.setText(DF.format(as.getHNA()));
                    ArcherySetupConfigurationActivity.this.asNockRaisingTxtFld.setText(DF.format(as.getNockRaising()));
                    ArcherySetupConfigurationActivity.this.asBraceHeightTxtFld.setText(DF.format(as.getBraceHeight()));
                    ArcherySetupConfigurationActivity.this.asDeltaTimeTxtFld.setText(DF.format(as.getDeltaTime()));
                    ArcherySetupConfigurationActivity.this.asCalcPrecisionTxtFld.setText(DF.format(as.getCalcPrecision()));
                    ArcherySetupConfigurationActivity.this.asSightVertScaleMiddleTxtFld.setText(DF.format(as.getSightVertSkalaMiddle()));
                    ArcherySetupConfigurationActivity.this.asSightHorzSettingTxtFld.setText(DF.format(as.getSightHorzSetting()));
                    ArcherySetupConfigurationActivity.this.selectedArcherySetup = as;
                }

                @Override
                public void onNothingSelected(final AdapterView<?> parent) { }
            });
    }


    private void addButtonListeners() {

        this.newBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(final View v) {
                    onNewArcherySetup();
                }
            });

        this.saveBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(final View v) {
                    onSaveArcherySetup();
                }
            });

        this.deleteBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(final View v) {
                    onDeleteArcherySetup();
                }
            });
    }

    /**
     * Löschen.
     */
    protected void onDeleteArcherySetup() {

        if (this.selectedArcherySetup != null) {

            android.content.DialogInterface.OnClickListener deleteBtnListener = new android.content.DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    try {
                        ArcherySetupDao.getInstance().delete(ArcherySetupConfigurationActivity.this.selectedArcherySetup);
                        loadArcherySetupSpinner();
                    } catch (Exception e) {
                        Toast toast = Toast.makeText(ArcherySetupConfigurationActivity.this,
                                                     getResources().getString(R.string.caption_Cfg_DeleteNotPossible), Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                    }
                }
            };

            AlertDialog dlg = PlatformUtils.getDeleteConfirmDialog(this, this.selectedArcherySetup.toString(), deleteBtnListener);
            dlg.show();
        }
    }

    /**
     * Speichern.
     */
    protected void onSaveArcherySetup() {
        if (this.selectedArcherySetup != null) {
            if (!this.asLabelTxtFld.getText().toString().isEmpty() && this.asSightSpinner.getSelectedItem() != null
                && this.asRiserSpinner.getSelectedItem() != null && !this.asArrowDiameterTxtFld.getText().toString().isEmpty()
                && !this.asArrowCwTxtFld.getText().toString().isEmpty() && !this.asArrowWeightTxtFld.getText().toString().isEmpty()
                && !this.asArrowV0TxtFld.getText().toString().isEmpty() && !this.asArrowCenterHeightTxtFld.getText().toString().isEmpty()
                && !this.asArrowNockHeightTxtFld.getText().toString().isEmpty() && !this.asBowPulloutTxtFld.getText().toString().isEmpty()
                && !this.ashNATxtFld.getText().toString().isEmpty() && !this.asNockRaisingTxtFld.getText().toString().isEmpty()
                && !this.asBraceHeightTxtFld.getText().toString().isEmpty() && !this.asDeltaTimeTxtFld.getText().toString().isEmpty()
                && !this.asCalcPrecisionTxtFld.getText().toString().isEmpty() && !this.asSightVertScaleMiddleTxtFld.getText().toString().isEmpty()
                && !this.asSightHorzSettingTxtFld.getText().toString().isEmpty()) {

                this.selectedArcherySetup.setName(this.asLabelTxtFld.getText().toString());
                this.selectedArcherySetup.setSight(this.asSightSpinner.getSelectedSight());
                this.selectedArcherySetup.setRiser(this.asRiserSpinner.getSelectedRiser());
                this.selectedArcherySetup.setArrowDiameter(Double.valueOf(this.asArrowDiameterTxtFld.getText().toString()));
                this.selectedArcherySetup.setArrowCw(Double.valueOf(this.asArrowCwTxtFld.getText().toString()));
                this.selectedArcherySetup.setArrowWeight(Double.valueOf(this.asArrowWeightTxtFld.getText().toString()));
                this.selectedArcherySetup.setArrowV0(Double.valueOf(this.asArrowV0TxtFld.getText().toString()));
                this.selectedArcherySetup.setArrowCenterHeight(Double.valueOf(this.asArrowCenterHeightTxtFld.getText().toString()));
                this.selectedArcherySetup.setArrowNockHeight(Double.valueOf(this.asArrowNockHeightTxtFld.getText().toString()));
                this.selectedArcherySetup.setBowPullout(Double.valueOf(this.asBowPulloutTxtFld.getText().toString()));
                this.selectedArcherySetup.setHNA(Double.valueOf(this.ashNATxtFld.getText().toString()));
                this.selectedArcherySetup.setNockRaising(Double.valueOf(this.asNockRaisingTxtFld.getText().toString()));
                this.selectedArcherySetup.setBraceHeight(Double.valueOf(this.asBraceHeightTxtFld.getText().toString()));
                this.selectedArcherySetup.setDeltaTime(Double.valueOf(this.asDeltaTimeTxtFld.getText().toString()));
                this.selectedArcherySetup.setCalcPrecision(Double.valueOf(this.asCalcPrecisionTxtFld.getText().toString()));
                this.selectedArcherySetup.setSightVertSkalaMiddle(Double.valueOf(this.asSightVertScaleMiddleTxtFld.getText().toString()));
                this.selectedArcherySetup.setSightHorzSetting(Double.valueOf(this.asSightHorzSettingTxtFld.getText().toString()));

                try {
                    if (this.selectedArcherySetup.getId() > 0) {
                        ArcherySetupDao.getInstance().update(this.selectedArcherySetup);
                    } else {
                        this.selectedArcherySetup = ArcherySetupDao.getInstance().insert(this.selectedArcherySetup);
                        loadArcherySetupSpinner();
                        this.asArcherySetupSpinner.setSelectionByVal(this.selectedArcherySetup.getName());
                    }
                } catch (Exception e) {
                    Toast toast = Toast.makeText(this, getResources().getString(R.string.caption_Cfg_ArcherySetup_SaveNotPossible),
                                                 Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }

                setResult(1);
            } else {
                Toast toast = Toast.makeText(this, getResources().getString(R.string.caption_Cfg_FillAllMandatoryFields), Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        }
    }

    /**
     * Einfügen.
     */
    @SuppressWarnings("unchecked")
    protected void onNewArcherySetup() {
        IArcherySetup newArcherySetup = new ArcherySetup(0, "*", null, null, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d);

        this.selectedArcherySetup = newArcherySetup;
        ((FontArrayAdapter<IArcherySetup>) this.asArcherySetupSpinner.getAdapter()).add(newArcherySetup);
        this.asArcherySetupSpinner.setSelectionByVal(newArcherySetup.getName());
        this.asArrowDiameterTxtFld.setText("");
        this.asArrowCwTxtFld.setText("");
        this.asArrowWeightTxtFld.setText("");
        this.asArrowV0TxtFld.setText("");
        this.asArrowCenterHeightTxtFld.setText("");
        this.asBowPulloutTxtFld.setText("");
        this.asArrowNockHeightTxtFld.setText("");
        this.ashNATxtFld.setText("");
        this.asNockRaisingTxtFld.setText("");
        this.asBraceHeightTxtFld.setText("");
        this.asDeltaTimeTxtFld.setText("");
        this.asCalcPrecisionTxtFld.setText("");
        this.asSightVertScaleMiddleTxtFld.setText("");
        this.asSightHorzSettingTxtFld.setText("");
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        getMenuInflater().inflate(R.menu.rbs_info_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {

        // Handle item selection
        switch (item.getItemId()) {

        case R.id.itemAbout:
            showDialog(RBSMainActivity.DLG_ABOUT);
            return true;

        default:

            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected Dialog onCreateDialog(final int id) {
        return DialogFactory.createDialog(id, this);
    }
}
