/**
 * 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.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.database.dao.RiserDao;
import ch.spherIC.recurvebowsight.model.IRiser;
import ch.spherIC.recurvebowsight.model.Riser;
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 RiserConfigurationActivity extends Activity {

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

    private RiserSpinner rcRiserSpinner;
    private TextView rcManufacturerTxtFld;
    private TextView rcModelTxtFld;
    private TextView rcSizeTxtFld;
    private TextView rcVvisHTxtFld;
    private TextView rcVvisVTxtFld;

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

    private IRiser selectedRiser;

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

        initializeComponents();
        addRiserSpinnerListener();
        addButtonListeners();
        loadRiserSpinner();
    }

    private void loadRiserSpinner() {
        List<IRiser> risers = RiserDao.getInstance().loadAll();
        this.rcRiserSpinner.setAdapter(new FontArrayAdapter<IRiser>(this, R.layout.rbs_spinner, risers, this.rcRiserSpinner));
    }

    private void initializeComponents() {
        this.rcRiserSpinner = (RiserSpinner) findViewById(R.id.rcRiserSpinner);
        this.rcManufacturerTxtFld = (TextView) findViewById(R.id.rcManufacturerTxtFld);
        this.rcModelTxtFld = (TextView) findViewById(R.id.rcModelTxtFld);
        this.rcSizeTxtFld = (TextView) findViewById(R.id.rcSizeTxtFld);
        this.rcVvisHTxtFld = (TextView) findViewById(R.id.rcVvisHTxtFld);
        this.rcVvisVTxtFld = (TextView) findViewById(R.id.rcVvisVTxtFld);

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

    private void addRiserSpinnerListener() {

        this.rcRiserSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                @Override
                public void onItemSelected(final AdapterView<?> parent, final View view, final int position,
                                           final long id) {
                    IRiser riser = RiserConfigurationActivity.this.rcRiserSpinner.getSelectedRiser();
                    RiserConfigurationActivity.this.rcManufacturerTxtFld.setText(riser.getManufacturer());
                    RiserConfigurationActivity.this.rcModelTxtFld.setText(riser.getModel());
                    RiserConfigurationActivity.this.rcSizeTxtFld.setText(DF.format(riser.getSize()));
                    RiserConfigurationActivity.this.rcVvisHTxtFld.setText(DF.format(riser.getVVisH()));
                    RiserConfigurationActivity.this.rcVvisVTxtFld.setText(DF.format(riser.getVVisV()));
                    RiserConfigurationActivity.this.selectedRiser = riser;
                }

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


    private void addButtonListeners() {

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

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

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

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

        if (this.selectedRiser != null) {

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

    /**
     * Speichern.
     */
    protected void onSaveRiser() {
        if (this.selectedRiser != null) {
            if (!this.rcManufacturerTxtFld.getText().toString().isEmpty() && !this.rcModelTxtFld.getText().toString().isEmpty()
                && !this.rcSizeTxtFld.getText().toString().isEmpty() && !this.rcVvisHTxtFld.getText().toString().isEmpty()
                && !this.rcVvisVTxtFld.getText().toString().isEmpty()) {

                this.selectedRiser.setManufacturer(this.rcManufacturerTxtFld.getText().toString());
                this.selectedRiser.setModel(this.rcModelTxtFld.getText().toString());
                this.selectedRiser.setSize(Double.valueOf(this.rcSizeTxtFld.getText().toString()));
                this.selectedRiser.setVVisH(Double.valueOf(this.rcVvisHTxtFld.getText().toString()));
                this.selectedRiser.setVVisV(Double.valueOf(this.rcVvisVTxtFld.getText().toString()));
                if (this.selectedRiser.getId() > 0) {
                    RiserDao.getInstance().update(this.selectedRiser);
                } else {
                    this.selectedRiser = RiserDao.getInstance().insert(this.selectedRiser);
                    loadRiserSpinner();
                    this.rcRiserSpinner.setSelectedRiser(this.selectedRiser);
                }
                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 onNewRiser() {
        IRiser newRiser = new Riser(0, "*", "*", 0d, 0d, 0d);
        this.selectedRiser = newRiser;
        ((FontArrayAdapter<IRiser>) this.rcRiserSpinner.getAdapter()).add(newRiser);
        this.rcRiserSpinner.setSelectedRiser(newRiser);
        this.rcManufacturerTxtFld.setText("");
        this.rcModelTxtFld.setText("");
        this.rcSizeTxtFld.setText("");
        this.rcVvisHTxtFld.setText("");
        this.rcVvisVTxtFld.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);
    }
}
