package com.hyperling.carbupbeta;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
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.TextView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by usb on 9/28/14.
 *
 * This class will:
 *  Create a new list then open tab2
 */

public class Tab1 extends Activity{

    private DALIH dalih;

    // Layout related
    Context context;
    EditText txtList;
    Button btnCreate;
    LinearLayout layListArea;
    TextView tvLeft, tvRight, selectHeader;

    // The lists!
    ArrayList<List> lists = new ArrayList<List>();

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

        // Set default context
        context = this;

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

        // Connect to the layout
        txtList = (EditText) findViewById(R.id.etListName);
        btnCreate = (Button) findViewById(R.id.btnAddToList);
        layListArea = (LinearLayout) findViewById(R.id.tab1ListArea);
        tvLeft = (TextView) findViewById(R.id.leftEditView);
        tvRight = (TextView) findViewById(R.id.rightEditView);
        selectHeader = (TextView) findViewById(R.id.selectListHeader);

        return;
    }

    public void setButtonInsert(){
        btnCreate.setText(R.string.list_create_button_insert);
        tvLeft.setText("");
        tvRight.setText("");

        dalih.setLastItem();

        createLists();

        btnCreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ListInfo newList = new ListInfo();
                newList.setName(dalih.filterString(txtList.getText().toString()));

                if (!testDuplicate(newList)) {
                    if (dalih.DEBUG) System.out.println("List not duplicate, inserting");

                    hideKeyboard();

                    dalih.insertList(newList);

                    createLists();

                    dalih.setOpenTab(2);
                }
            }
        });

        return;
    }

    public void setButtonUpdate(final List list){
        btnCreate.setText(R.string.list_create_button_update);
        String editing = getString(R.string.list_editing) + " "; // strings.xml must get trimmed, space is not appearing
        tvLeft.setText(editing);
        tvRight.setText(list.getName());

        // Store the ID
        dalih.setLastItem(list.getID());

        // Recreate the lists
        createLists();

        // Pull the text
        txtList.setText(list.getName());

        showKeyboard();

        btnCreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.setName(dalih.filterString(txtList.getText().toString()));

                if (!testDuplicate(list)) {
                    if (dalih.DEBUG) System.out.println("List not duplicate, updating");

                    hideKeyboard();

                    dalih.updateList(list);

                    if (dalih.getLastList() == list.getID()) {
                        if (dalih.DEBUG) System.out.println("Last list renamed, resetting");

                        restart();
                    }

                    setButtonInsert();
                }
            }
        });

        return;
    }

    // Generate all lists and place in alphabetical order
    private void createLists(){
        if (dalih.DEBUG) System.out.println("Creating lists for Tab1");

        txtList.setText("");

        lists = new ArrayList<List>();

        for (ListInfo info : dalih.getLists()){
            if (dalih.DEBUG) System.out.println("Found list: " + info.getID() + " " +info.getName());

            if (info.getID() != dalih.getLastItem()) {
                lists.add(new List(context, info));
            }
        }

        if (lists.size() > 0){
            selectHeader.setText(R.string.list_select_header);
        }
        else{
            selectHeader.setText("");
        }

        lists = orderLists(lists);

        layListArea.removeAllViews();
        for (final List list : lists){
            list.btnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dalih.DEBUG) System.out.println("Clicked delete button: " + list.getID() + " " + list.getName());

                    dalih.deleteList(list);

                    if (dalih.getLastList() == list.getID()){
                        if (dalih.DEBUG) System.out.println("Last list deleted, resetting");

                        dalih.setLastList();

                        restart();
                    }

                    createLists();
                }
            });

            list.btnEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dalih.DEBUG) System.out.println("Clicked edit button: " + list.getID() + " " + list.getName());

                    // Change to update mode
                    setButtonUpdate(list);
                }
            });

            list.btnItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dalih.DEBUG) System.out.println("Clicked main button: " + list.getID() + " " + list.getName());

                    dalih.setLastList(list.getID());

                    dalih.setOpenTab(2);

                    //restart();
                    startActivity(new Intent(Tab1.this, Main.class));
                }
            });

            if (dalih.DEBUG) System.out.println("Creating list: " + list.getID() + " " + list.getName());

            layListArea.addView(list.getView());
        }

        return;
    }

    private ArrayList<List> orderLists(ArrayList<List> unorderedLists){
        if (dalih.DEBUG) System.out.println("Sorting lists");

        ArrayList<List> orderedLists = new ArrayList<>();

        while (!unorderedLists.isEmpty()) {
            String bestName = "z";
            int index = 0;

            for (List list : unorderedLists) {
                if (list.getName().toUpperCase().compareTo(bestName.toUpperCase()) < 0) {
                    //if (dalih.DEBUG) System.out.println(list.getName() + " is better than " + bestName);

                    bestName = list.getName();
                    index = unorderedLists.indexOf(list);
                }
            }
            if (dalih.DEBUG) System.out.println(bestName + " was the best");

            orderedLists.add(unorderedLists.get(index));
            unorderedLists.remove(index);
        }

        return orderedLists;
    }

    private boolean testDuplicate(ListInfo listInfo) {
        for (List list : lists) {
            if (listInfo.getName().equals(list.getName()) || listInfo.getName().equals("")) {
                Toast.makeText(context, "Name must be unique!", Toast.LENGTH_SHORT).show();
                return true;
            }
        }

        return false;
    }

    private void restart(){
        finish();
        startActivity(new Intent(Tab1.this, Main.class));

        return;
    }

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

        dalih.open();

        setButtonInsert();

        super.onResume();

        return;
    }

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

        dalih.close();

        hideKeyboard();

        super.onPause();

        return;
    }

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

        return;
    }

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

        return;
    }
}
