using UnityEngine;
using System.Collections;

public class GrowingThing : MonoBehaviour {

    public Texture m_emission = null;
    public Sprite[ ] m_sprites = null;
    public Sprite[ ] m_rotting = null;
    public float m_intervalDuration = 0.25f;
    public Timer m_timer = new Timer( );
    public Timer m_rottingTimer = new Timer( );
    public SpriteRenderer m_renderer = null;
    public int m_spriteIndex = 0;
    public int m_rottingIndex = 0;
    public bool m_isRotting = false;
    private Material m_material = null;

    public void Start( ) {
        m_material = m_renderer.material;
    }

    public void initialize( ) {

        m_sprites = null;
        m_rotting = null;
        m_intervalDuration = 0.25f;
        m_timer = new Timer( );
        m_rottingTimer = new Timer( );
        m_spriteIndex = 0;
        m_rottingIndex = 0;
        m_isRotting = false;
        gameObject.SetActive( false );
    }

    public void startGrowing( float duration ) {

        gameObject.SetActive( true );
        m_spriteIndex = 0;
        m_intervalDuration = duration / ( m_sprites.Length - 1 );
        m_renderer.sprite = m_sprites[ m_spriteIndex ];
        m_timer.start( m_intervalDuration );
        m_isRotting = false;

        if ( m_material == null ) {
            m_material = m_renderer.material;
        }

        m_material.SetTexture( "_EmissionMap", m_emission );
    }

    public void startRotting( float duration ) {

        m_rottingIndex = 0;
        m_intervalDuration = duration / ( m_rotting.Length - 1 );
        m_renderer.sprite = m_rotting[ m_rottingIndex ];
        m_rottingTimer.start( m_intervalDuration );
        m_isRotting = true;
    }

	void Update( ) {

        m_timer.step( );
        m_rottingTimer.step( );

        if ( m_timer.isEndedOnce( ) ) {

            m_spriteIndex++;
            m_renderer.sprite = m_sprites[ m_spriteIndex ];

            if ( m_spriteIndex < m_sprites.Length - 1 ) {
                m_timer.start( m_intervalDuration );
            }
        }

        if ( m_rottingTimer.isEndedOnce( ) ) {

            m_rottingIndex++;
            m_renderer.sprite = m_rotting[ m_rottingIndex ];

            if ( m_rottingIndex < m_rotting.Length - 1 ) {
                m_rottingTimer.start( m_intervalDuration );
            }
        }
	}

    public bool isFullyGrown( ) {

        bool result = gameObject.activeInHierarchy && m_spriteIndex >= m_sprites.Length - 1;
        return result;
    }

    public bool isDead( ) {
        bool result = m_isRotting && m_rottingIndex >= m_rotting.Length - 1;
        return result;
    }
}
