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

public class uTweenController : MonoBehaviour 
{
    public Transform[] targets;

    Dictionary<string, List<uTweener>> tweenerDic = new Dictionary<string, List<uTweener>>();

    List<uTweener> activeTweenerList = new List<uTweener>();

    int activeTweenCount = 0;

    [System.NonSerialized]
    public float duration;

    [SerializeField]
    bool playOnAwake = false;

    public void Awake()
    {
        duration = 0;
        tweenerDic.Clear();
        for (int i = 0; i < targets.Length; i++)
        {
            if (null != targets[i])
            {
                uTweener[] tweeners = targets[i].GetComponents<uTweener>();
                for (int j = 0; j < tweeners.Length; j++)
                {
                    AddTweener(tweeners[j]);
                    float totalTime = tweeners[j].duration + tweeners[j].delay;
                    if (totalTime > duration) duration = totalTime;
                }
            }
            else
            {
                UnityEngine.Debug.Log("<color=red>" + gameObject.name + "上面uTweenController的Targets里面有空的对象！</color>");
            }
        }
    }

    void OnEnable()
    {
        if (playOnAwake && Application.isPlaying)
        {
            Play();
        }
    }

    void AddTweener(uTweener tweener)
    {
        string tag = tweener.tag;
        if (!tweenerDic.ContainsKey(tag))
        {
            tweenerDic[tag] = new List<uTweener>();
        }
        tweenerDic[tag].Add(tweener);
    }

    /// <summary>
    /// 播放所有动画
    /// </summary>
    /// <param name="delay">延迟</param>
    public void Play(float delay)
    {
        activeTweenerList.Clear();
        foreach (var tweeners in tweenerDic)
        {
            for (int i = 0; i < tweeners.Value.Count; i++)
            {
                uTweener tweener = tweeners.Value[i];
                if (!tweener.gameObject.activeSelf)
                {
                    continue;
                }
                tweener.delay = delay;
                tweener.ResetToBeginning();
                tweener.PlayForward();
                if (tweener.updateStyle == uTweener.UpdateStyle.Other)
                {
                    activeTweenerList.Add(tweener);
                }
            }
        }
        activeTweenCount = activeTweenerList.Count;
    }

    public void PlayForward(bool isNeedReset)
    {
        activeTweenerList.Clear();
        foreach (var tweeners in tweenerDic)
        {
            for (int i = 0; i < tweeners.Value.Count; i++)
            {
                uTweener tweener = tweeners.Value[i];
                if (!tweener.gameObject.activeSelf)
                {
                    continue;
                }
                if (isNeedReset)
                {
                    tweener.ResetToBeginning();
                }
                tweener.PlayForward();
                if (tweener.updateStyle == uTweener.UpdateStyle.Other)
                {
                    activeTweenerList.Add(tweener);
                }
            }
        }
        activeTweenCount = activeTweenerList.Count;
    }

    /// <summary>
    /// 播放所有动画
    /// </summary>
    public void Play()
    {
        activeTweenerList.Clear();
        foreach (var tweeners in tweenerDic)
        {
            for (int i = 0; i < tweeners.Value.Count; i++)
            {
                uTweener tweener = tweeners.Value[i];
                if (!tweener.gameObject.activeSelf)
                {
                    continue;
                }
                tweener.ResetToBeginning();
                tweener.PlayForward();
                if (tweener.updateStyle == uTweener.UpdateStyle.Other)
                {
                    activeTweenerList.Add(tweener);   
                }                
            }
        }
        activeTweenCount = activeTweenerList.Count;
    }

    public void PlayReverse()
    {
        PlayReverse(true);
    }

    public void PlayReverse(string tag)
    {
        activeTweenerList.Clear();
        for (int i = 0, j = tweenerDic[tag].Count; i < j; i++)
        {
            uTweener tweener = tweenerDic[tag][i];
            if (!tweener.gameObject.activeSelf)
            {
                continue;
            }
            tweener.PlayReverse();
            if (tweener.updateStyle == uTweener.UpdateStyle.Other)
            {
                activeTweenerList.Add(tweener);
            }
        }
        activeTweenCount = activeTweenerList.Count;
    }

    /// <summary>
    /// 反向播放所有动画
    /// </summary>
    /// <param name="isNeedReset">是否需要重置到反向开始时的位置</param>
    public void PlayReverse(bool isNeedReset)
    {
        activeTweenerList.Clear();
        foreach (var tweeners in tweenerDic)
        {
            for (int i = 0; i < tweeners.Value.Count; i++)
            {
                uTweener tweener = tweeners.Value[i];
                if (!tweener.gameObject.activeSelf)
                {
                    continue;
                }
                if (isNeedReset)
                {
                    tweener.ResetToEnd();
                }
                tweener.PlayReverse();
                if (tweener.updateStyle == uTweener.UpdateStyle.Other)
                {
                    activeTweenerList.Add(tweener);
                }                
            }
        }
        activeTweenCount = activeTweenerList.Count;
    }

    [ContextMenu("ResetToBeginning")]
	public void ResetToBeginning()
	{
		foreach (var tweeners in tweenerDic)
		{
			for (int i = 0; i < tweeners.Value.Count; i++)
			{
				uTweener tweener = tweeners.Value[i];
				tweener.ResetToBeginning();
			}
		}
	}

	public void ResetToBeginning(string tag)
	{
		if (tweenerDic.ContainsKey(tag))
		{
			List<uTweener> list = tweenerDic[tag];
			for (int i = 0; i < list.Count; i++)
			{
				uTweener tweener = list[i];
				tweener.ResetToBeginning();
			}
		}
	}

    [ContextMenu("ResetToEnd")]
	public void ResetToEnd()
	{
		foreach (var tweeners in tweenerDic)
		{
			for (int i = 0; i < tweeners.Value.Count; i++)
			{
				uTweener tweener = tweeners.Value[i];
				tweener.ResetToEnd();
			}
		}
	}

	public void ResetToEnd(string tag)
	{
		if (tweenerDic.ContainsKey(tag))
		{
			List<uTweener> list = tweenerDic[tag];
			for (int i = 0; i < list.Count; i++)
			{
				uTweener tweener = list[i];
				tweener.ResetToEnd();
			}
		}
	}

    /// <summary>
    /// 播放指定名字的动画
    /// </summary>
    /// <param name="tag"></param>
    public void Play(string tag, float delay)
    {
        if (!tweenerDic.ContainsKey(tag))
        {
            UnityEngine.Debug.Log(string.Format("找不到{0}上的{1}动画！", gameObject.name, tag));
            return;
        }
        else 
        {
            activeTweenerList.Clear();
            for (int i = 0, j = tweenerDic[tag].Count; i < j; i++)
            {
                uTweener tweener = tweenerDic[tag][i];
                if (!tweener.gameObject.activeSelf)
                {
                    continue;
                }
                tweener.delay = delay;
                tweener.ResetToBeginning();
                tweener.PlayForward();
                if (tweener.updateStyle == uTweener.UpdateStyle.Other)
                {
                    activeTweenerList.Add(tweener);
                }                
            }
            activeTweenCount = activeTweenerList.Count;
        }
    }

    public void Play(string tag)
    {
        if (!tweenerDic.ContainsKey(tag))
        {
            UnityEngine.Debug.Log(string.Format("找不到{0}上的{1}动画！", gameObject.name, tag));
            return;
        }
        else
        {
            activeTweenerList.Clear();
            for (int i = 0, j = tweenerDic[tag].Count; i < j; i++)
            {
                uTweener tweener = tweenerDic[tag][i];
                if (!tweener.gameObject.activeSelf)
                {
                    continue;
                }
                tweener.ResetToBeginning();
                tweener.PlayForward();
                if (tweener.updateStyle == uTweener.UpdateStyle.Other)
                {
                    activeTweenerList.Add(tweener);
                }
            }
            activeTweenCount = activeTweenerList.Count;
        }
    }

	public void PlayWithoutActive()
	{
		activeTweenerList.Clear();
		foreach (var tweeners in tweenerDic)
		{
			for (int i = 0; i < tweeners.Value.Count; i++)
			{
				uTweener tweener = tweeners.Value[i];
				tweener.ResetToBeginning();
				tweener.PlayForward();
				if (tweener.updateStyle == uTweener.UpdateStyle.Other)
				{
					activeTweenerList.Add(tweener);
				}
			}
		}
		activeTweenCount = activeTweenerList.Count;
	}

	public void PlayWithoutActive(string tag)
	{
		if (!tweenerDic.ContainsKey(tag))
		{
			UnityEngine.Debug.Log(string.Format("找不到{0}上的{1}动画！", gameObject.name, tag));
			return;
		}
		else
		{
			activeTweenerList.Clear();
			for (int i = 0, j = tweenerDic[tag].Count; i < j; i++)
			{
				uTweener tweener = tweenerDic[tag][i];
				tweener.ResetToBeginning();
				tweener.PlayForward();
				if (tweener.updateStyle == uTweener.UpdateStyle.Other)
				{
					activeTweenerList.Add(tweener);
				}
			}
			activeTweenCount = activeTweenerList.Count;
		}
	}

    public void Stop()
    {
        activeTweenerList.Clear();
        foreach (var item in tweenerDic)
        {
            for (int i = 0; i < item.Value.Count; i++)
            {
                item.Value[i].enabled = false;
            }
        }
        activeTweenCount = 0;
    }

    public void Stop(string tag)
    {
        if (!tweenerDic.ContainsKey(tag))
        {
            UnityEngine.Debug.Log(string.Format("找不到{0}上的{1}动画！", gameObject.name, tag));
            return;
        }
        else
        {
            activeTweenerList.Clear();
            for (int i = 0, j = tweenerDic[tag].Count; i < j; i++)
            {
                uTweener tweener = tweenerDic[tag][i];
                tweener.enabled = false;
            }
            activeTweenCount = 0;
        }
    }

    public void SetTweenState(bool state)
    {
        foreach (var list in tweenerDic.Values)
        {
            foreach (var tween in list)
            {
                tween.enabled = state;
            }
        }
    }


    [System.NonSerialized]
    public string animName;

    [SerializeField]
    float m_progress;

    float currentTime;

    [System.NonSerialized]
    public string[] names;

    [System.NonSerialized]
    public int currentIndex = 0;

    [System.NonSerialized]
    public float playBackSpeed = 1;

    public float Progress
    {
        get
        {
            return m_progress;
        }
        set
        {
            m_progress = value;
            currentTime = duration * m_progress;
            SetAnim();
        }
    }

    void SetAnim()
    {
        if (null == animName) animName = allName;
        if (animName != allName)
        {
            if(tweenerDic.ContainsKey(animName))
            {
                for (int i = 0; i < tweenerDic[animName].Count; i++)
                {
                    uTweener tweener = tweenerDic[animName][i];
                    if (!tweener.gameObject.activeSelf)
                    {
                        continue;
                    }
                    float delay = tweener.delay;
                    if (currentTime < delay) continue;
                    float duration = tweener.duration;
                    float factor = (currentTime - delay) / duration;
                    if (factor > 1) continue;
                    tweener.tweenFactor = factor;
                    if (tweener.enabled)
                    {
                        tweener.gameObject.SetActive(false);
                        tweener.gameObject.SetActive(true);
                    }
                }
            }
        }
        else
        {
            foreach (var item in tweenerDic)
            {
                for (int i = 0; i < item.Value.Count; i++)
                {
                    uTweener tweener = item.Value[i];
                    if (!tweener.gameObject.activeSelf)
                    {
                        continue;
                    }
                    float delay = tweener.delay;
                    if (currentTime < delay) continue;
                    float duration = tweener.duration;
                    float factor = (currentTime - delay) / duration;
                    if (factor > 1) continue;
                    tweener.tweenFactor = factor;
                    if (tweener.enabled)
                    {
                        tweener.gameObject.SetActive(false);
                        tweener.gameObject.SetActive(true);
                    }
                }
            }
        }
    }

    const string allName = "All";

    public string[] GetAnimNames()
    {
        string[] names = new string[tweenerDic.Count + 1];
        names[0] = allName;
        int currentIndex = 1;
        foreach (var item in tweenerDic)
        {
            names[currentIndex] = item.Key;
            currentIndex++;
        }
        return names;
    }
}
