using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class MenuSystem : MonoBehaviour 
{
    public static string GAME_NAME = "Adventures of One";

    public enum State
    {
        Intro,
        PreBattle,
        Battle,
        Shop,
        PostBattle, // Shows win or loss
        LoadSave
    };

    public static bool InBattle
    {
        get { return Instance.m_state == State.Battle; }
    }
    public static bool InIntro
    {
        get { return Instance.m_state == State.Intro; }
    }


    public bool m_postBattleWon;
    bool m_shopPurchase;

    public static MenuSystem ms_instance;
    public static MenuSystem Instance
    {
        get { return ms_instance; }
    }

    State m_state;

	// Use this for initialization
	void Start ()
    {
        if (ms_instance != null)
        {
            Debug.LogError("Only one menusys allowed");
        }
        ms_instance = this;

        m_state = State.Intro;

        VoiceManager.Instance.Play(4);
	}

    string m_currentSavegameData = "";

    public void SetState(State newState)
    {
        m_state = newState;

        if ( m_state == State.PreBattle )
        {
            PlayerObject.Instance.SaveToPlayerPrefs();
            m_currentSavegameData = PlayerObject.Instance.Info.ConvertToString();
        }
    }

    void Update()
    {

    }
	
	// Update is called once per frame
	void OnGUI () 
    {
        switch (m_state)
        {
            case State.Intro:
                {
                    DrawIntro();
                }
                break;
            case State.Battle:
                {
                    DrawBattle();
                }
                break;
            case State.PreBattle:
                {
                    DrawPreBattle();
                }
                break;
            case State.Shop:
                {
                    DrawShop();
                }
                break;
            case State.PostBattle:
                {
                    DrawPostBattle();
                }
                break;
            case State.LoadSave:
                {
                    DrawLoadSave();
                }
                break;
        }
	}

    void DrawSplash()
    {
        const int HEADING_WIDTH = 400;
        const int CENTRE_HEIGHT = 225;

        string headingText = "\"" + MenuSystem.GAME_NAME + "\"\n";
        headingText += "\n";
        headingText += "Tactical Strategy On Your Lonesome";

        headingText += "\n";
        headingText += "\n";
        headingText += "A game written for Ludum Dare #22\n";
        headingText += "by Gavin Pugh (Drebin)\n";
        headingText += "http://www.gavpugh.com/\n";
        headingText += "\n";
        headingText += "\n";
        headingText += "Voiceover by Juliette Danielle";
        headingText += "\n";
        headingText += "\n";
        if (m_state != State.Intro)
        {
            headingText += string.Format("\nCurrent Battle : Battle #{0}", PlayerObject.Instance.Info.m_battleNumber);
            headingText += string.Format("\nCurrent Gold : {0}", PlayerObject.Instance.Info.m_gold);
        }

        int xPos = (Screen.width - HEADING_WIDTH) / 2;
        int yPos = (Screen.height - CENTRE_HEIGHT) / 4;
        GUI.Box(new Rect(xPos, (Screen.height - CENTRE_HEIGHT) / 4, HEADING_WIDTH, CENTRE_HEIGHT), headingText);        
    }

    void DrawIntro()
    {
        DrawSplash();

        const int HEADING_WIDTH = 400;
        const int CENTRE_HEIGHT = 225;
        int xPos = (Screen.width - HEADING_WIDTH) / 2;
        int yPos = (Screen.height - CENTRE_HEIGHT) / 4;

        yPos += CENTRE_HEIGHT + 30;

        const int BUTTON_WIDTH = 80;
        const int BUTTON_HEIGHT = 60;

        if (GUI.Button(new Rect((Screen.width - BUTTON_WIDTH) / 2, yPos, BUTTON_WIDTH, BUTTON_HEIGHT), "Continue"))
        {
            SetState(State.PreBattle);
        }
    }


    void DrawPreBattle()
    {
        DrawSplash();

        const int HEADING_WIDTH = 400;
        const int CENTRE_HEIGHT = 225;
        int xPos = (Screen.width - HEADING_WIDTH) / 2;
        int yPos = (Screen.height - CENTRE_HEIGHT) / 4;

        yPos += CENTRE_HEIGHT + 30;

        const int BUTTON_WIDTH = 80;
        const int BUTTON_HEIGHT = 60;
        const int NUM_BUTTONS = 4;

        const int BUTTON_SEP = (HEADING_WIDTH - (BUTTON_WIDTH * NUM_BUTTONS)) / (NUM_BUTTONS - 1);

        if (GUI.Button(new Rect(xPos, yPos, BUTTON_WIDTH, BUTTON_HEIGHT), "Start\nBattle!"))
        {
            SFXManager.MenuSelect();
            BeginBattle();
        }
        xPos += BUTTON_WIDTH + BUTTON_SEP;
        if (GUI.Button(new Rect(xPos, yPos, BUTTON_WIDTH, BUTTON_HEIGHT), "Save \\\nLoad \\\nReset"))
        {
            SFXManager.MenuSelect();
            SetState(State.LoadSave);
        }
        xPos += BUTTON_WIDTH + BUTTON_SEP;
        if (GUI.Button(new Rect(xPos, yPos, BUTTON_WIDTH, BUTTON_HEIGHT), "Buy From\nShop"))
        {
            SFXManager.MenuSelect();
            m_shopPurchase = true;
            BeginShop();

        }
        xPos += BUTTON_WIDTH + BUTTON_SEP;
        if (GUI.Button(new Rect(xPos, yPos, BUTTON_WIDTH, BUTTON_HEIGHT), "Sell To\nShop"))
        {
            SFXManager.MenuSelect();
            m_shopPurchase = false;
            BeginShop();
        }
    }

    void DrawShop()
    {
        m_scrollChoice.OnGUI();

        CharacterInfo info = PlayerObject.Instance.Info;

        int index;
        if (m_scrollChoice.HasChosen(out index))
        {
            SFXManager.MenuSelect();

            if (index >= 0)
            {
                if (m_shopPurchase)
                {
                    // ItemID
                    CharacterItem item = CharacterItem.GetItem((ItemID)index);

                    if ( item.m_cost <= info.m_gold )
                    {
                        info.m_gold -= item.m_cost;
                        info.m_inventory.Add((ItemID)index);
                    }
                    else
                    {
                        // Not enough cash
                        GuiStatusText.DisplayText("Not enough cash for: " + item.m_name, GuiStatusText.DEFAULT_TIME);
                    }
                }
                else
                {
                    // Inv index selling
                    CharacterItem item = CharacterItem.GetItem( info.m_inventory[index]);
                    info.m_inventory.RemoveAt(index);
                    info.m_gold += item.SellCost;
                }

                // Redraw shop
                BeginShop();
            }
            else
            {
                SetState(State.PreBattle);
            }
        }
    }

    void DrawBattle()
    {
        // Do nowt
    }

    void DrawPostBattle()
    {
        const int HEADING_WIDTH = 400;
        const int CENTRE_HEIGHT = 160;

        string headingText = "\"" + MenuSystem.GAME_NAME + "\"\n";
        headingText += "\n";
        headingText += "\n";

        if ( m_postBattleWon )
        {
            headingText += "Congratulations!";
            headingText += "\n";
            headingText += "Milo, you alone have defeated all the enemies on this\n";
            headingText += "particular plane of Argon.\n";
            headingText += "\n";
            headingText += "The forces of darkness do not rest.\nPlease prepare for the next battle.";
        }
        else
        {
            headingText += "Milo is Dead!";
            headingText += "\n";
            headingText += "It is fortunate that the Gods of Argon allow him to be\n";
            headingText += "resurrected. Milo will also retain any experience and\n";
            headingText += "gold you managed to obtain in battle.\n";
            headingText += "\n";
            headingText += "Now, get ready to give this one another try.";
        }
        
        int xPos = (Screen.width - HEADING_WIDTH) / 2;
        int yPos = (Screen.height - CENTRE_HEIGHT) / 4;
        GUI.Box(new Rect(xPos, (Screen.height - CENTRE_HEIGHT) / 4, HEADING_WIDTH, CENTRE_HEIGHT), headingText);

        yPos += CENTRE_HEIGHT + 30;

        const int BUTTON_WIDTH = 80;
        const int BUTTON_HEIGHT = 60;

        if (GUI.Button(new Rect((Screen.width - BUTTON_WIDTH) / 2, yPos, BUTTON_WIDTH, BUTTON_HEIGHT), "Continue"))
        {
            SetState(State.PreBattle);
        }
    }
    
    void BeginBattle()
    {
        SetState(State.Battle);
        BattleManager.Instance.StartBattle();
    }

    GuiScrollChoice m_scrollChoice = new GuiScrollChoice();

    void BeginShop()
    {
        CharacterInfo info = PlayerObject.Instance.Info;
        int gold = info.m_gold;
        SetState(State.Shop);

        if ( m_shopPurchase )
        {
            m_scrollChoice.NewChoiceMenuCaption( string.Format("Purchase Items - Current Gold: {0}", gold) );

            foreach( KeyValuePair<ItemID,CharacterItem> kvp in CharacterItem.ms_items)
            {
                CharacterItem item = kvp.Value;
                if (item.m_cost > 0)
                {
                    // Crude way to lock out the more expensive stuff...
                    if ( item.m_cost <= info.m_maxGoldEver )
                    {
                        m_scrollChoice.Add((int)kvp.Key, string.Format("{0} ({1})", item.m_name, (item.m_cost)));
                    }
                }
            }
        }
        else
        {
            m_scrollChoice.NewChoiceMenuCaption(string.Format("Sell Items - Current Gold: {0}", gold));

            for ( int i=0;i<info.m_inventory.Count;i++ )
            {
                CharacterItem item = CharacterItem.GetItem( info.m_inventory[i]);
                if ( item.m_cost > 0 )
                {
                    m_scrollChoice.Add( i, string.Format( "{0} ({1})", item.m_name, ( item.SellCost ) ) );
                }
            }
        }
    }

    public void DrawLoadSave()
    {
        //const int SAVE_THING_WIDTH = 700;
        const int HEADING_WIDTH = 400;

        const int BUTTON_WIDTH = 120;
        const int BUTTON_HEIGHT = 60;

        int xPos = 120;
        int yPos = 50;
        int CENTRE_HEIGHT = Screen.height - yPos - BUTTON_HEIGHT - 40;
        GUI.Label(new Rect(xPos, 0, HEADING_WIDTH, 50), "Current save data shown below.\nThis can be copy and pasted to another machine.");
        m_currentSavegameData = GUI.TextArea(new Rect(xPos, yPos, Screen.width - xPos, CENTRE_HEIGHT), m_currentSavegameData);

        yPos += CENTRE_HEIGHT + 30;

         const int NUM_BUTTONS = 3;

         const int BUTTON_SEP = (HEADING_WIDTH - (BUTTON_WIDTH * NUM_BUTTONS)) / (NUM_BUTTONS - 1);

         if (GUI.Button(new Rect(xPos, yPos, BUTTON_WIDTH, BUTTON_HEIGHT), "(be careful)\nLoad From\nPasted Text"))
         {
             SFXManager.MenuSelect();
             PlayerObject.Instance.LoadFromString( m_currentSavegameData);
             SetState(State.PreBattle);
         }
         xPos += BUTTON_WIDTH + BUTTON_SEP;
         if (GUI.Button(new Rect(xPos, yPos, BUTTON_WIDTH, BUTTON_HEIGHT), "(be careful)\nReset Player\nTo Factory"))
         {
             SFXManager.MenuSelect();
             PlayerObject.Instance.SetupPlayerDefaults();
             SetState(State.PreBattle);
         }
         xPos += BUTTON_WIDTH + BUTTON_SEP;
         if (GUI.Button(new Rect(xPos, yPos, BUTTON_WIDTH, BUTTON_HEIGHT), "Go Back"))
         {
             SFXManager.MenuSelect();
             SetState(State.PreBattle);
         }

    }

}
