﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEditor;

[RequireComponent(typeof(Animation))]
public class T1AnimationAssistant : MonoBehaviour
{
    //public T1AnimEventMonoAction[] keyFrames = new T1AnimEventMonoAction[0];
    public T1AnimEventMonoClip[] animations = new T1AnimEventMonoClip[0];

    public void OnValidate()
    {
        for (int i = 0; i < animations.Length; i++)
        {
            AnimationClip clip = animations[i].animClip;
            if (clip != null)
            {
                //Set AnimID by tag in the name of the AnimationClip file if theres one
                //Match match = Regex.Match(clip.name, @"\[([0-9]+)\]");
                //if (match.Success)
                //{
                //    int result;
                //    if (int.TryParse(match.Groups[1].Value, out result))
                //        animations[i].animID = result;
                //}

                //Set Frame number from 1 to max animation frame count
                int frameCount = clip.empty ? 2 : Mathf.Max(Mathf.FloorToInt(clip.length * 15.0f) + 1, 2);
                for (int j = 0; j < animations[i].keyFrames.Length; j++)
                {
                    animations[i].keyFrames[j].frame = (uint)Mathf.Clamp(animations[i].keyFrames[j].frame, 1, frameCount - 1);
                }
            }
        }
    }

    void Reset()
    {
        AnimationClip[] animClips = AnimationUtility.GetAnimationClips(gameObject);
        for (int i = 0; i < animClips.Length; i++)
        {
            if (animClips[i] != null)
            {
                T1AnimEventMonoClip anim = new T1AnimEventMonoClip();
                anim.animClip = animClips[i];
                ArrayUtility.Add(ref animations, anim);
            }
        }

        OnValidate();
    }
}

[Serializable]
public class T1AnimEventMonoClip
{
    public AnimationClip animClip;
    public int animID;
    public bool loop;
    public T1AnimKeyFrameAction[] keyFrames = new T1AnimKeyFrameAction[0];
}
