/**
 * Copyright (C) 2005-2012 XELOG AG
 */
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.database.sqlite.SQLiteConstraintException;

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.SightSpinner;
import ch.spherIC.recurvebowsight.database.dao.SightDao;
import ch.spherIC.recurvebowsight.model.ISight;
import ch.spherIC.recurvebowsight.model.Sight;
import ch.spherIC.recurvebowsight.utilities.CompatibilityUtil;
import ch.spherIC.recurvebowsight.utilities.PlatformUtils;

import java.text.DecimalFormat;

import java.util.List;


/**
 * @author  FC Smilari
 */
public class SightConfigurationActivity extends Activity {

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

    private SightSpinner scSightSpinner;
    private TextView scManufacturerTxtFld;
    private TextView scModelTxtFld;
    private TextView sccHeVSTxtFld;
    private TextView sccaVTxtFld;
    private TextView sccaHTxtFld;
    private TextView scVertScaleRngMinTxtFld;
    private TextView scVertScaleRngMaxTxtFld;

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

    private ISight selectedSight;

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

        initializeComponents();
        addSightSpinnerListener();
        addButtonListeners();
        loadSightSpinner();
    }

    private void loadSightSpinner() {
        List<ISight> sights = SightDao.getInstance().loadAll();
        this.scSightSpinner.setAdapter(new FontArrayAdapter<ISight>(this, R.layout.rbs_spinner, sights, this.scSightSpinner));
    }

    private void initializeComponents() {
        this.scSightSpinner = (SightSpinner) findViewById(R.id.scSightSpinner);
        this.scManufacturerTxtFld = (TextView) findViewById(R.id.scManufacturerTxtFld);
        this.scModelTxtFld = (TextView) findViewById(R.id.scModelTxtFld);
        this.sccHeVSTxtFld = (TextView) findViewById(R.id.sccHeVSTxtFld);
        this.sccaVTxtFld = (TextView) findViewById(R.id.sccaVTxtFld);
        this.sccaHTxtFld = (TextView) findViewById(R.id.sccaHTxtFld);
        this.scVertScaleRngMinTxtFld = (TextView) findViewById(R.id.scVertScaleRngMinTxtFld);
        this.scVertScaleRngMaxTxtFld = (TextView) findViewById(R.id.scVertScaleRngMaxTxtFld);

        this.newBtn = (Button) findViewById(R.id.scBtnNew);
        this.saveBtn = (Button) findViewById(R.id.scBtnSave);
        this.deleteBtn = (Button) findViewById(R.id.scBtnDelete);
    }

    private void addSightSpinnerListener() {

        this.scSightSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                @Override
                public void onItemSelected(final AdapterView<?> parent, final View view, final int position,
                                           final long id) {
                    ISight sight = SightConfigurationActivity.this.scSightSpinner.getSelectedSight();
                    SightConfigurationActivity.this.scManufacturerTxtFld.setText(sight.getManufacturer());
                    SightConfigurationActivity.this.scModelTxtFld.setText(sight.getModel());
                    SightConfigurationActivity.this.sccHeVSTxtFld.setText(sight.getHeVis());
                    SightConfigurationActivity.this.sccaVTxtFld.setText(DF.format(sight.getAV()));
                    SightConfigurationActivity.this.sccaHTxtFld.setText(DF.format(sight.getAH()));
                    SightConfigurationActivity.this.scVertScaleRngMinTxtFld.setText(DF.format(sight.getVertSkalaRangeMin()));
                    SightConfigurationActivity.this.scVertScaleRngMaxTxtFld.setText(DF.format(sight.getVertSkalaRangeMax()));
                    SightConfigurationActivity.this.selectedSight = sight;
                }

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


    private void addButtonListeners() {

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

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

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

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

        if (this.selectedSight != null) {

            android.content.DialogInterface.OnClickListener deleteBtnListener = new android.content.DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    try {
                        SightDao.getInstance().delete(SightConfigurationActivity.this.selectedSight);
                        loadSightSpinner();
                    } catch (SQLiteConstraintException e) {
                        Toast toast = Toast.makeText(SightConfigurationActivity.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.selectedSight.toString(), deleteBtnListener);
            dlg.show();
        }
    }

    /**
     * Speichern.
     */
    protected void onSaveSight() {
        if (this.selectedSight != null) {
            if (!this.scManufacturerTxtFld.getText().toString().isEmpty() && !this.scModelTxtFld.getText().toString().isEmpty()
                && !this.sccHeVSTxtFld.getText().toString().isEmpty() && !this.sccaVTxtFld.getText().toString().isEmpty()
                && !this.sccaHTxtFld.getText().toString().isEmpty() && !this.scVertScaleRngMinTxtFld.getText().toString().isEmpty()
                && !this.scVertScaleRngMaxTxtFld.getText().toString().isEmpty()) {

                this.selectedSight.setManufacturer(this.scManufacturerTxtFld.getText().toString());
                this.selectedSight.setModel(this.scModelTxtFld.getText().toString());
                this.selectedSight.setHeVis(this.sccHeVSTxtFld.getText().toString());
                this.selectedSight.setAV(Double.valueOf(this.sccaVTxtFld.getText().toString()));
                this.selectedSight.setAH(Double.valueOf(this.sccaHTxtFld.getText().toString()));
                this.selectedSight.setVertSkalaRangeMin(Double.valueOf(this.scVertScaleRngMinTxtFld.getText().toString()));
                this.selectedSight.setVertSkalaRangeMax(Double.valueOf(this.scVertScaleRngMaxTxtFld.getText().toString()));

                if (this.selectedSight.getId() > 0) {
                    SightDao.getInstance().update(this.selectedSight);
                } else {
                    this.selectedSight = SightDao.getInstance().insert(this.selectedSight);
                    loadSightSpinner();
                    this.scSightSpinner.setSelectedSight(this.selectedSight);
                }
                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 onNewSight() {
        ISight newSight = new Sight(0, "*", "*", 0d, 0d, "", 0d, 0d);
        this.selectedSight = newSight;
        ((FontArrayAdapter<ISight>) this.scSightSpinner.getAdapter()).add(newSight);
        this.scSightSpinner.setSelectedSight(newSight);
        this.scManufacturerTxtFld.setText("");
        this.scModelTxtFld.setText("");
        this.sccHeVSTxtFld.setText("");
        this.sccaVTxtFld.setText("");
        this.sccaHTxtFld.setText("");
        this.scVertScaleRngMinTxtFld.setText("");
        this.scVertScaleRngMaxTxtFld.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);
    }
}
