using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;

public struct Vec2i {
    public int x;
    public int y;
}

public class Main : MonoBehaviour {

    public GameObject m_interactButton = null;
    public ShowHideButton m_showHideInteractButton = null;
    public ShowHideButton m_cropHint = null;
    public ShowHideButton m_harvestButton = null;
    public ShowHideButton m_carryButton = null;
    public ShowHideButton m_dropButton = null;
    public ShowHideButton m_send = null;
    public GameObject m_camera = null;
    public Image m_wantedImage = null;
    public Sprite[ ] m_wantedSprites = null;
    private bool m_isCarrying = false;
    private float m_carryingFactor = 1.0f;
    private MapData m_mapData = null;
    private static Main ms_instance = null;
    public Player m_player = null;
    public GameObject m_letter = null;
    public Text m_letterText = null;
    public SourisBehaviour m_mouse = null;
    private bool m_firstTime = true;
    public Timer m_firstTimeTimer = new Timer( );
    public Audio m_audio = null;
    private bool m_gameOver = false;
    public Animation m_letterBox = null;
    private int m_maxField = 5;

    private int m_childCount = 1;
    private int m_sentToFamily = 0;
    private float m_sentToGod = 0.0f;

    public static Main get( ) {
        return ms_instance;
    }

    void Awake( ) {
        ms_instance = this;
    }

    void Start( ) {
        m_mapData = MapData.get( );
        m_letterText.text = "Walter my dear,\n\nTimes are hard down here, but I'm sure every thing is going to be ok. I just saw the doctor this morning, and Walter Junior will arrive on time if you send me enough vegetables (1 should be plenty for now).\n\nI hope we'll be together soon.\n\n\nYour love, Louise";
        m_letter.SetActive( true );
        m_mapData.m_maxField = m_maxField;
    }

	void Update( ) {

        if ( m_firstTime ) {

            if ( m_letter.activeInHierarchy ) {

                if ( Input.GetKeyUp( KeyCode.Space ) ) {
                    m_letter.SetActive( false );
                    m_firstTimeTimer.start( 7.5f );
                }
            }

            m_firstTimeTimer.step( );

            if ( m_firstTimeTimer.isEndedOnce( ) ) {
                m_mouse.m_paused = false;
                m_firstTime = false;
            }
        }

        bool showInteract = false;
        bool showHarvest = false;
        Vec2i v = m_mapData.getNearestField( m_player.transform.position );

        if ( m_mapData.doesFieldExists( v ) && m_mapData.isFieldEnabled( v.x, v.y ) ) {

            Field f = m_mapData.getField( v.x, v.y ).GetComponent<Field>( );
            float distance = ( f.transform.position - m_player.transform.position ).sqrMagnitude;

            if ( distance < 4.0f * 4.0f ) {

                if ( f.m_planted == CropType.none ) {

                    m_interactButton.transform.position = f.transform.position + new Vector3( 0.0f, 0.5f, 0.0f );
                    spriteOrientation( m_interactButton.transform );
                    showInteract = true;

                    if ( Input.GetKey( KeyCode.Alpha1 ) ) {
                        f.plant( CropType.Turnip );
                        Audio.play( m_audio.plant );
                    } else if ( Input.GetKey( KeyCode.Alpha2 ) ) {
                        f.plant( CropType.Carrot );
                        Audio.play( m_audio.plant );
                    } else if ( Input.GetKey( KeyCode.Alpha3 ) ) {
                        f.plant( CropType.Strawberry );
                        Audio.play( m_audio.plant );
                    }

                } else if ( !m_isCarrying && f.isReadyToHarvest( )  ) {

                    m_harvestButton.transform.parent.position = f.transform.position + new Vector3( 0.0f, 0.5f, 0.0f );
                    spriteOrientation( m_harvestButton.transform.parent );

                    if ( !f.isFullyDead( ) ) {

                        showHarvest = true;

                        if ( Input.GetKey( KeyCode.E ) ) {

                            Audio.play( m_audio.pop );
                            m_carryingFactor = 1.0f;

                            if ( f.m_wanted != f.m_planted ) {
                                m_carryingFactor = 0.25f;
                            }

                            f.harvest( );
                            m_carryButton.show( );
                            m_carryButton.m_image.sprite = m_wantedSprites[ ( int ) ( f.m_planted ) - 1 ];
                            m_isCarrying = true;
                            showHarvest = false;
                            m_player.m_animator.SetBool( "carrying", true );
                        }

                    } else {

                       f.hideBasketIcon( );
                    }
                }
            }
        }

        if ( m_isCarrying ) {

            m_dropButton.show( );

            if ( m_player.transform.position.sqrMagnitude < 25.0f ) {

                m_send.show( );
                bool sent = false;

                if ( Input.GetKey( KeyCode.Alpha1 ) ) {

                    Audio.play( m_audio.cash );
                    m_sentToGod += m_carryingFactor;
                    sent = true;

                } else if ( Input.GetKey( KeyCode.Alpha3 ) ) {

                    Audio.play( m_audio.bite );
                    m_sentToFamily += 1;
                    sent = true;
                }

                if ( sent ) {

                    m_letterBox.Play( );
                    m_dropButton.hide( );
                    m_carryButton.hide( );
                    m_isCarrying = false;
                    m_player.m_animator.SetBool( "carrying", false );
                    m_send.hide( );
                }
            }
        }

        if ( showInteract ) {
            m_showHideInteractButton.show( );
        } else {
            m_showHideInteractButton.hide( );
        }

        if ( showHarvest ) {
            m_harvestButton.show( );
        } else {
            m_harvestButton.hide( );
        }

        spriteOrientation( m_wantedImage.transform.parent );
        spriteOrientation( m_carryButton.transform.parent );

        spriteOrientation( m_dropButton.transform.parent );
        spriteOrientation( m_send.transform.parent );

        if ( m_mapData.allFinished( ) && !m_isCarrying ) {

            if ( !m_letter.activeInHierarchy ) {

                int deadChild = 0;
                int sentToGod = ( int ) m_sentToGod;

                // m_letterText.text = "Child count: " + m_childCount + "\n";
                // m_letterText.text += "Sent to family: " + m_sentToFamily + "\n";
                // m_letterText.text += "Sent to Peter: " + m_sentToGod + "\n";
                int previousChildCount = m_childCount;

                if ( sentToGod < m_maxField * 0.5f ) {

                    if ( m_childCount > 1 ) {

                        if ( m_sentToFamily < m_childCount ) {
                            deadChild = m_sentToFamily - m_childCount;
                            m_childCount += deadChild;
                        }

                        if ( m_childCount > 1 ) {

                            m_childCount--;
                            deadChild++;
                            // m_letterText.text += "killed dead child: " + deadChild;
                            m_letterText.text = "Walter, some guy came to the house today and took one of our childs. I'm so scared, I don't know what to do.\n";

                            if ( deadChild > 1 ) {

                                for ( int i = 1; i < deadChild; i++ ) {
                                    m_letterText.text += "Junior " + ( previousChildCount + i ) + " ";
                                }

                                m_letterText.text += " starved to death. Please send " + m_childCount + " vegetables if you want us to live.";
                            }

                            m_letterText.text += "\n\n\nLouise";

                        } else {

                            m_letterText.text = "Dear Sir,\n\n I am saddened to announce the death of your wife Louise";

                            if ( deadChild > 2 ) {
                                m_letterText.text += " and your childs.\n\n";
                            } else {
                                m_letterText.text += " and your child.\n\n";
                            }

                            m_letterText.text += "C. K.";
                            m_gameOver = true;
                        }

                    } else {

                        m_letterText.text = "Dear Sir,\n\n I am saddened to announce the death of your wife Louise.\n\nC. K.";
                        m_gameOver = true;
                    }

                } else {

                    if ( m_sentToFamily !=  m_childCount ) {

                        deadChild = m_sentToFamily - m_childCount;
                        m_childCount += deadChild;

                        if ( m_childCount <= 0 ) {

                            m_letterText.text = "Dear Sir,\n\n I am saddened to announce the death of your wife Louise.\nShe appeared to have starved to death.\n\nC. K.";
                            m_gameOver = true;

                        } else {

                            if ( deadChild > 0 ) {
                                // m_letterText.text += "new born" + deadChild;
                                m_letterText.text = "Walter my dear,\n\nsay hello to our new child";

                                if ( deadChild > 1 ) {
                                    m_letterText.text += "s ";
                                } else {
                                    m_letterText.text += " ";
                                }

                                for ( int i = 0; i < deadChild; i++ ) {
                                    m_letterText.text += "Junior " + ( previousChildCount + i ) + " ";
                                }

                                m_letterText.text += "\nMore mouth to feed means more work for you, but it surely worth it! " + m_childCount + " vegetables should be enough.\n\nYour love, Louise";

                            } else {

                                m_letterText.text = "Walter,\nwe just lost ";

                                for ( int i = 0; i < -deadChild; i++ ) {
                                    m_letterText.text += "Junior " + ( previousChildCount + i ) + " ";
                                }

                                m_letterText.text += "\nI just didn't have enough food.\n\nPlease, can you send us " + m_childCount + " vegetables.\n\nLouise";
                            }
                        }

                    } else {

                        m_letterText.text = "Walter my dear,\n\nWhat would I do without you ? Starvation is strong in the region but thanks to your vegetables I'm alive and well. Keep them coming.\n\nYour love, Louise";
                    }

                }

                // m_letterText.text += "Child count: " + m_childCount + "\n";
                // m_letterText.text += "Sent to family: " + m_sentToFamily + "\n";
                // m_letterText.text += "Sent to Peter: " + m_sentToGod + "\n";

                m_letter.SetActive( true );

            } else {

                if ( Input.GetKeyUp( KeyCode.Space ) ) {

                    if ( m_gameOver ) {
                        SceneManager.LoadScene( "TitleScreen" );
                    }

                    m_mapData.reset( );
                    m_mouse.reset( );
                    m_letter.SetActive( false );
                    m_sentToFamily = 0;
                    m_sentToGod = 0.0f;
                    m_maxField += 2;

                    if ( m_maxField > 24 ) {
                        m_maxField = 24;
                    }

                    m_mapData.m_maxField = m_maxField;
                }
            }
        }
	}

    public void spriteOrientation( Transform t ) {

        Vector3 cameraGround = m_camera.transform.position;
        cameraGround.y = 0.0f;
        Vector3 transformGround = t.position;
        transformGround.y = 0.0f;

        Vector3 direction = transformGround - cameraGround;
        Quaternion rotation = Quaternion.identity;
        rotation.SetLookRotation( direction.normalized, Vector3.up  );
        t.rotation = rotation;
    }

    public void showWanted( Field field ) {

        m_cropHint.hide( );
        m_wantedImage.sprite = m_wantedSprites[ ( ( int ) field.m_wanted ) - 1 ];
        m_wantedImage.transform.parent.position = field.transform.position + new Vector3( 0.0f, 1.5f, 0.0f );
        m_cropHint.show( );
    }

    public void hideWanted( Field field ) {
        m_cropHint.hide( );
    }
}
