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

[System.Serializable]
public class AnimationCycle
{
    public string AnimationName;
    public List<Sprite> Sprites;
    public float FrameDuration;
}

public class Animatable : MonoBehaviour {

    public List<AnimationCycle> Animations;
    public bool StartIdle=true;
    public string DEBUG;

    private AnimationCycle currCycle;
    private int currIdx =0;
    private SpriteRenderer rend;
    private SpriteRenderer Rend { get { if (rend == null) rend = GetComponent<SpriteRenderer>(); return rend; } }
    private float offset;
    private float lastSwitch;

    void Start()
    {
        offset = Random.Range(0, 0.99f); // prevents anims from globally syncing on Time clock
        if(StartIdle)
            Animate("Idle");
    }

    public string GetCurrentAnimationFrame()
    {
        if (currCycle == null)
            return "";
        else
            return currCycle.AnimationName + "." + currIdx;
    }

    void Animate(string anim)
    {
        AnimationCycle cycle = Animations.Where(c => c.AnimationName == anim).FirstOrDefault();
        if (cycle == currCycle)
            return;

        if(cycle == null || cycle.Sprites.Count == 0)
        {
            if (anim != "Idle")
                Animate("Idle");
            return;
        }
        DEBUG = anim;
        currCycle = cycle;
        Rend.sprite = cycle.Sprites[0];
        currIdx =0;
        lastSwitch = Time.time;
        if (anim == "Idle")
            lastSwitch -= offset * currCycle.FrameDuration;
    }

    void Update()
    {
        CheckFrameChange();
    }

    private void CheckFrameChange()
    {
        if (currCycle == null || currCycle.Sprites.Count < 2)
            return;

        if (Time.time >= lastSwitch + currCycle.FrameDuration)
            AdvanceFrame();
    }

    private void AdvanceFrame()
    {
        if (currCycle == null || currCycle.Sprites.Count == 0)
            return;

        currIdx = (currIdx + 1) % currCycle.Sprites.Count;
        Rend.sprite = currCycle.Sprites[currIdx];
        lastSwitch = Time.time;
    }

}
