package com.hyperling.carbupbeta;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by usb on 9/28/14.
 *
 * This class will:
 *  Add items to the current selected list
 *
 *  DEEMED "GOOD ENOUGH" 13:45 2014-09-30 :D
 *      ListItems are created perfectly, ordered by Cal/$, and colored by Carb/Cal
 */

public class Tab2 extends Activity{

    private DALIH dalih;

    // Define the Views
    Context context;
    LinearLayout layListArea;
    EditText txtName, txtCost, txtServings, txtCalories, txtCarbs, txtFiber;
    Button btnClear, btnAdd;

    // List
    ArrayList<ListItem> items = new ArrayList<ListItem>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab2);

        // Set default context
        context = this;

        // Initiate DALIH
        dalih = new DALIH(context);

        // Load/Find the Views!
        layListArea = (LinearLayout) findViewById(R.id.layTab2ListArea);
        txtName = (EditText) findViewById(R.id.etItemName);
        txtCost = (EditText) findViewById(R.id.etItemCost);
        txtServings = (EditText) findViewById(R.id.etItemServs);
        txtCalories = (EditText) findViewById(R.id.etItemCals);
        txtCarbs = (EditText) findViewById(R.id.etItemCarbs);
        txtFiber = (EditText) findViewById(R.id.etItemFiber);
        btnClear = (Button) findViewById(R.id.btnClear);
        btnAdd = (Button) findViewById(R.id.btnAddToList);

        // Give the Buttons their power
        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                removeItem();

                // Clear all fields!
                txtName.setText("");
                txtCost.setText("");
                txtServings.setText("");
                txtCalories.setText("");
                txtCarbs.setText("");
                txtFiber.setText("");

                setButtonInsert();
            }
        });

        return;
    }// end onCreate

    @Override
    protected void onResume(){
        if (dalih.DEBUG) System.out.println("***** Resuming Tab2 *****");

        dalih.open();

        setButtonInsert();

        super.onResume();

        return;
    }

    @Override
    protected void onPause(){
        if (dalih.DEBUG) System.out.println("***** Pausing Tab2 *****");

        dalih.close();

        hideKeyboard();

        super.onPause();

        return;
    }

    public boolean validateItem(ListItemInfo newItem){
        // FIELDS MUST HAVE VALUES BEFORE CONVERTING!!!
        if (txtName.getText().toString().equals("")){
            Toast.makeText(context, "Item must have a name!", Toast.LENGTH_SHORT).show();
        }
        else if (txtCost.getText().toString().equals("") || txtCost.getText().toString().equals(".")){
            Toast.makeText(context, "Item must have a cost!", Toast.LENGTH_SHORT).show();
        }
        else if (txtServings.getText().toString().equals("") || txtServings.getText().toString().equals(".")){
            Toast.makeText(context, "Item must have servings!", Toast.LENGTH_SHORT).show();
        }
        else if (txtCalories.getText().toString().equals("") || txtCalories.getText().toString().equals(".")){
            Toast.makeText(context, "Item must have calories!", Toast.LENGTH_SHORT).show();
        }
        else if (txtCarbs.getText().toString().equals("") || txtCarbs.getText().toString().equals(".")){
            Toast.makeText(context, "Item must have carbohydrates!", Toast.LENGTH_SHORT).show();
        }
        else{

            newItem.setName(txtName.getText().toString());
            newItem.setCost(Double.parseDouble(txtCost.getText().toString()));
            newItem.setServings(Double.parseDouble(txtServings.getText().toString()));
            newItem.setCalories(Double.parseDouble(txtCalories.getText().toString()));
            newItem.setCarbs(Double.parseDouble(txtCarbs.getText().toString()));
            newItem.setFiber(Double.parseDouble(txtFiber.getText().toString()));
            newItem.setListID(dalih.getLastList());

            // NAME MUST BE UNIQUE, VALUES MUST BE GREATER THAN 0
            boolean nameDuplicated = false;
            for(ListItem li : items){
                if(newItem.getName().equals(li.getName()) || newItem.getName().equals("")){
                    nameDuplicated = true;
                }
            }
            if (nameDuplicated){
                Toast.makeText(context, "Name must be unique!", Toast.LENGTH_SHORT).show();
            }
            else if (newItem.getCost() <= 0){
                Toast.makeText(context, "Cost must be greater than 0!", Toast.LENGTH_SHORT).show();
            }
            else if (newItem.getServings() <= 0){
                Toast.makeText(context, "Servings must be greater than 0!", Toast.LENGTH_SHORT).show();
            }
            else if (newItem.getCalories() <= 0){
                Toast.makeText(context, "Calories must be greater than 0!", Toast.LENGTH_SHORT).show();
            }
            else if (newItem.getFiber() > newItem.getCarbs()){
                Toast.makeText(context, "Cannot have more fiber than carbs!", Toast.LENGTH_SHORT).show();
            }
            else if ((newItem.getCarbs()-newItem.getFiber()) * 3.5 > newItem.getCalories()){
                Toast.makeText(context, "Too many carbs, not enough calories!", Toast.LENGTH_SHORT).show();
            }
            else{
                return true;
            }// end else
        }// end else

        return false;
    }// end validateItem()

    public void setButtonInsert(){
        btnAdd.setText(R.string.item_create_button_insert);

        // Reset to default
        dalih.setLastItem();

        createItems();

        if (dalih.DEBUG) System.out.println("Setting add button to insert");
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ListItemInfo newItem = new ListItemInfo();

                if (validateItem(newItem)) {
                    hideKeyboard();

                    dalih.insertItem(newItem);

                    createItems();

                    dalih.setOpenTab(1);
                }
            }
        });// end btnAdd.setOnClickListener

        return;
    }

    public void setButtonUpdate(final ListItem listItem){
        btnAdd.setText(R.string.item_create_button_update);

        // Pull Item info into top boxes then remove the ListItem
        // Save which item we are on
        dalih.setLastItem(listItem.getID());

        // Remove the item
        createItems();

        // Set all fields to the values
        txtName.setText(listItem.getName());
        txtCost.setText(Double.toString(listItem.getCost()));
        txtServings.setText(Double.toString(listItem.getServings()));
        txtCalories.setText(Double.toString(listItem.getCalories()));
        txtCarbs.setText(Double.toString(listItem.getCarbs()));
        txtFiber.setText(Double.toString(listItem.getFiber()));

        showKeyboard();

        if (dalih.DEBUG) System.out.println("");
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (validateItem(listItem)) {
                    hideKeyboard();

                    dalih.updateItem(listItem);

                    setButtonInsert();
                }
            }
        });// end btnAdd.setOnClickListener

        return;
    }

    public void createItems(){
        if (dalih.DEBUG) System.out.println("Creating items");

        txtName.setText("");
        txtCost.setText("");
        txtServings.setText("");
        txtCalories.setText("");
        txtCarbs.setText("");
        txtFiber.setText("");

        items = new ArrayList<ListItem>();

        for (ListItemInfo info : dalih.getItems(dalih.getLastList())){
            if (dalih.DEBUG) System.out.println("Found item: " + info.getID() + " " + info.getName());

            // Prevent item being edited from being displayed
            if (info.getID() != dalih.getLastItem()) {
                items.add(new ListItem(context, info));
            }
        }

        // ========== Display the ListItems ==========
        // Order the list
        items = orderList(items);

        // Give the Item Buttons functionality
        for (final ListItem li : items){
            li.btnEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Change the create button to update instead of insert
                    setButtonUpdate(li);
                }
            });

            li.btnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dalih.deleteItem(li);

                    createItems();
                }
            });
        }

        // Replace old List with new ordered list
        // Clear list
        layListArea.removeAllViews();
        // Add Views
        for (ListItem li : items) {
            layListArea.addView(li.getView());
        }

        return;
    }

    public ArrayList<ListItem> orderList(ArrayList<ListItem> unorderedList){
        if (dalih.DEBUG) System.out.println("Sorting the items");

        ArrayList<ListItem> orderedList = new ArrayList<ListItem>();

        while (!unorderedList.isEmpty()) {
            double max = 0;
            int index = 0;

            for (ListItem j : unorderedList) {
                if (j.getCalPerDol() > max) {
                    //if (dalih.DEBUG) System.out.println(j.getCalPerDol()*100 + " is better than " + max*100);

                    max = j.getCalPerDol();
                    index = unorderedList.indexOf(j);
                }
            }
            if (dalih.DEBUG) System.out.println(max*100 + " was the best");
            orderedList.add(unorderedList.get(index));
            unorderedList.remove(index);
        }

        return orderedList;
    }

    public void removeItem(){
        int deleteID = dalih.getLastItem();

        for (ListItemInfo item : dalih.getItems(dalih.getLastList())){
            if (item.getID() == deleteID){
                if (dalih.DEBUG) System.out.println("Deleting item " + item.getID() + " " + item.getName());
                dalih.deleteItem(item);
                break;
            }
        }

        return;
    }

    public void hideKeyboard(){
        ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(btnAdd.getWindowToken(),0);

        return;
    }

    public void showKeyboard(){
        ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(txtName, 0);

        return;
    }

}// end Tab2
