using UnityEngine;
using System.Collections;

public class Effect : MonoBehaviour {
	
	Direction direction;
	const float MAX_TIME = 0.4f;
	float timer;
	int currentSprite = 0;
	int currentSide = 0;
	
	public class Frames{
		public Sprite[] sprite;	
		public Frames(int count){
			sprite = new Sprite[count];
		}
		public void HideAll(){
			for(int i = 0; i < sprite.Length; i++) {
				sprite[i].visible = false;
			}
		}
	}
	Frames[] frames = new Frames[4];
	
	Sprite CreateSprite(Coordinate tileUV, Vector3 position){		
		return Tile.CreateChar(transform, tileUV, position);
	}
	
	void CreateAnimations(
		Coordinate rightUV, 
		Coordinate downUV, 
		Coordinate leftUV, 
		Coordinate upUV,
		int frameCount){
		frames[0] = new Frames(frameCount);
		frames[1] = new Frames(frameCount);
		frames[2] = new Frames(frameCount);
		frames[3] = new Frames(frameCount);	
		for(int i = 0; i < frameCount; i++){
			frames[0].sprite[i] = CreateSprite(new Coordinate(rightUV.x, rightUV.y 	+ i), new Vector3( 1, 0, -0.5f) * Tile.TILE_SIZE);
			frames[1].sprite[i] = CreateSprite(new Coordinate(downUV.x , downUV.y 	+ i), new Vector3( 0,-1, -0.5f) * Tile.TILE_SIZE);
			frames[2].sprite[i] = CreateSprite(new Coordinate(leftUV.x , leftUV.y 	+ i), new Vector3(-1, 0, -0.5f) * Tile.TILE_SIZE);
			frames[3].sprite[i] = CreateSprite(new Coordinate(upUV.x   , upUV.y 	+ i), new Vector3( 0, 1, -0.5f) * Tile.TILE_SIZE);
		}	
		for(int i = 0; i < 4; i++){
			frames[i].HideAll();
		}
	}

	void Start () {
		CreateAnimations(
			new Coordinate(0, 2),
			new Coordinate(1, 2),
			new Coordinate(2, 2),
			new Coordinate(3, 2),
			7);
	}
	
	public void Use(int side){		
		if (timer <= 0) {
			currentSide = side;
			timer = MAX_TIME;
		}
	}
	
	void Update () {
		if (timer > 0) {
			timer -= Time.deltaTime;
			frames[currentSide].sprite[currentSprite].visible = false;
			currentSprite = 6 - (int)(timer * 7f / MAX_TIME);
			if (currentSprite >= 7){
				currentSprite = 6;
			}
			frames[currentSide].sprite[currentSprite].visible = true; 
			if (timer <= 0) {
				timer = 0;
				frames[currentSide].sprite[currentSprite].visible = false; 
			//	timer = MAX_TIME; 
			}
		}
	}
}
