using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Playables;

public class AnimatedPanel : MonoBehaviour, IPanelSetup, IAnimationClipSource
{
    public AnimationClip open;
    public AnimationClip close;

    private Panel panel;
    private PlayableGraph graph;
    private float closeStartedTime;
    private bool currentOpen;

    public void SetupPanel(Panel panel)
    {
        this.panel = panel;

        panel.onOpen += () =>
        {
            if (!currentOpen)
            {
                PlayAnimation(open);
                currentOpen = true;
            }
        };

        panel.onClose += () =>
        {
            if (currentOpen)
            {
                panel.gameObject.SetActive(true);
                PlayAnimation(close);
                closeStartedTime = Time.time;
                currentOpen = false;
            }
        };
    }

    private void LateUpdate()
    {
        if (!panel.isOpen & Time.time > closeStartedTime + close.length)
        {
            panel.gameObject.SetActive(false);
        }
    }

    public void PlayAnimation(AnimationClip clip)
    {
        if (graph.IsValid())
        {
            graph.Destroy();
        }

        graph = PlayableGraph.Create();
        var animationPlayableOutput = AnimationPlayableOutput.Create(graph, "Animation", GetComponent<Animator>());
        var animationClipPlayable = AnimationClipPlayable.Create(graph, clip);

        animationPlayableOutput.SetSourcePlayable(animationClipPlayable);
        graph.Play();
    }

    public void StopAnimation()
    {
        if (graph.IsValid())
        {
            graph.Destroy();
        }
    }

    private void OnDisable()
    {
        if (graph.IsValid())
        {
            graph.Destroy();
        }
    }

    private void OnDestroy()
    {
        if (graph.IsValid())
        {
            graph.Destroy();
        }
    }

    private void Reset()
    {
        panel = GetComponent<Panel>();
    }

    public void GetAnimationClips(List<AnimationClip> results)
    {
        results.Add(open);
        results.Add(close);
    }
}