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

public class ShamanScript : MonoBehaviour {

	public delegate void ListEvent(List<Direction> directionList,int shamanId);
    public static event ListEvent OnListUpdated; 

    List<Direction> directionList;
    const int MAXLISTCOUNT = 10;
	DirectionContainerScript container;

	KeyCode [] keys;
	int id;

	public Sprite[] shamanFrames;

	public void SetData(KeyCode [] keys,int id)
	{
		this.keys = keys;
		this.id = id;
	}

	void OnEnable(){
		DemonScript.matches += DemonScript_matches;
	}

	void OnDisable(){
		DemonScript.matches -= DemonScript_matches;
	}

	void DemonScript_matches (int firstMatch, int enemyComboSize,int shamanId)
	{
		if(id == shamanId)
		{
		foreach(Direction i in directionList)	
			Debug.Log (i);
		for (int i = 0; i < enemyComboSize; i++) {
			directionList.RemoveAt(firstMatch);
		}
		container.RemoveDirection (firstMatch,enemyComboSize);
		}
	}

    void Awake()
    {
        directionList = new List<Direction>();
		container = (DirectionContainerScript)Instantiate(GlobalObjects.directionContainerPrefab,Vector3.zero,Quaternion.identity);
		container.transform.SetParent(transform);
		container.transform.localPosition = new Vector3(0,1,-1);
    }

	// Update is called once per frame
	void Update () {
		
        CheckKeys();
	}

    void CheckKeys()
    {

		if (Input.GetKeyDown(keys[0]))
            AddKeyToList(Direction.Up);
		else if (Input.GetKeyDown(keys[1]))
            AddKeyToList(Direction.Right);
		else if (Input.GetKeyDown(keys[2]))
            AddKeyToList(Direction.Down);
		else if (Input.GetKeyDown(keys[3]))
            AddKeyToList(Direction.Left);
    }

    void AddKeyToList(Direction dict)
    {
        if (directionList.Count > MAXLISTCOUNT)
        {
            Debug.Log("Siliniyor: " + directionList[0]);
            directionList.RemoveAt(0);
			container.RemoveDirection (0,1);
        }
        directionList.Add(dict);
        Debug.Log("Ekleniyor: "+dict);
		CreateDirectionObjects (dict);

		gameObject.GetComponent<SpriteRenderer> ().sprite=shamanFrames[Random.Range(0,shamanFrames.Length)];

        if (OnListUpdated != null)
        {
            OnListUpdated(directionList,id);

            Debug.Log("OnListUpdated event fired!");
        }
    }

	private void CreateDirectionObjects(Direction dict)
	{
			container.AddDirection(dict);
	}
}
