using System;
using UnityEngine;

public class ClosedLetter : MonoBehaviour
{
    [SerializeField]
    private Transform _topPartTransform;

    [SerializeField]
    private tk2dBaseSprite _stamp;

    private Animator mAnimator;
    private float mInitialY;
    private float mFinalY;
    private Action mOnOpenedAction;
    private Action mOnClosedAction;

    private void Awake()
    {
        mAnimator = GetComponent<Animator>();
        mAnimator.enabled = false;
        mInitialY = _topPartTransform.localPosition.y;
    }

    private void PlayAnimation(ClosedLetterAnimations animation)
    {
        mAnimator.enabled = true;
        mAnimator.Play(animation.ToString());
    }

    public void OnOpened()
    {
        mOnOpenedAction();
        mOnOpenedAction = null;
        mAnimator.enabled = false;

        mFinalY = _topPartTransform.localPosition.y;
    }

    public void OnClosed()
    {
        mOnClosedAction();
        mOnClosedAction = null;
        mAnimator.enabled = false;
    }

    public void Prepare(ClosedLetterAnimations animationToPlay, Attributes? attribute)
    {
        _topPartTransform.localPosition = new Vector3(_topPartTransform.localPosition.x, animationToPlay == ClosedLetterAnimations.Opening ? mInitialY : mFinalY , _topPartTransform.localPosition.z);

        Stamps stampToSet = default(Stamps);
        if (attribute.HasValue)
        {
            stampToSet = attribute.Value.GetStamp();
        }
        else
        {
            stampToSet = Stamps.King;
        }

        _stamp.spriteId = (int)stampToSet;
    }

    public void Open(Action onOpenedAction)
    {
        Sound.PlayLetterOpening();

        mOnOpenedAction = onOpenedAction;
        PlayAnimation(ClosedLetterAnimations.Opening);
    }

    public void Close(Action onClosedAction)
    {
        mOnClosedAction = onClosedAction;
        PlayAnimation(ClosedLetterAnimations.Closing);
    }
}