using UnityEngine;
using System.Collections;

[RequireComponent(typeof(ITouchable))]
public class DarkeningEffect : ITouchableEffects
{
    private const float DARKENING = 100.0f / 255.0f;
    private Color[] INITIAL_COLOR_TEXTS, INITIAL_COLOR_SPRITES, FINAL_COLOR_TEXTS, FINAL_COLOR_SPRITES;
    private tk2dTextMesh[] mTexts;
    private tk2dBaseSprite[] mSprites;
    private bool mFirstTouch = true;

	void Start () 
    {
        mTexts = GetComponentsInChildren<tk2dTextMesh>();
        mSprites = GetComponentsInChildren<tk2dBaseSprite>();
	}

    private void CreateColorVectors()
    {
        INITIAL_COLOR_TEXTS = new Color[mTexts.Length];
        FINAL_COLOR_TEXTS = new Color[mTexts.Length];
        for (int i = 0; i < mTexts.Length; i++)
        {
            INITIAL_COLOR_TEXTS[i] = mTexts[i].color;
            FINAL_COLOR_TEXTS[i] = new Color(INITIAL_COLOR_TEXTS[i].r - DARKENING, INITIAL_COLOR_TEXTS[i].g - DARKENING, INITIAL_COLOR_TEXTS[i].b - DARKENING);
        }

        INITIAL_COLOR_SPRITES = new Color[mSprites.Length];
        FINAL_COLOR_SPRITES = new Color[mSprites.Length];
        for (int i = 0; i < mSprites.Length; i++)
        {
            INITIAL_COLOR_SPRITES[i] = mSprites[i].color;
            FINAL_COLOR_SPRITES[i] = new Color(INITIAL_COLOR_SPRITES[i].r - DARKENING, INITIAL_COLOR_SPRITES[i].g - DARKENING, INITIAL_COLOR_SPRITES[i].b - DARKENING);
        }
    }

    public override void OnTouchBegan()
    {
        //if (mFirstTouch)
        {
            CreateColorVectors();
            mFirstTouch = false;
        }
        for (int i = 0; i < mTexts.Length; i++)
        {
            mTexts[i].color = FINAL_COLOR_TEXTS[i];
            mTexts[i].Commit();
        }
        for (int i = 0; i < mSprites.Length; i++)
        {
            mSprites[i].color = FINAL_COLOR_SPRITES[i];
        }
    }

    public override void OnTouchEnded()
    {
        for (int i = 0; i < mTexts.Length; i++)
        {
            mTexts[i].color = INITIAL_COLOR_TEXTS[i];
            mTexts[i].Commit();
        }
        for (int i = 0; i < mSprites.Length; i++)
        {
            mSprites[i].color = INITIAL_COLOR_SPRITES[i];
        }
    }
}