using System;
using UnityEngine;
using mgaia.Utils;
using mgaia.Utils.Animations;

public class Postman : MonoBehaviour
{
    [SerializeField]
    private Transform _startingPosition;

    [SerializeField]
    private Transform _endingPosition;

    private tk2dSpriteAnimator mAnimator;
    private Action mOnDeliverAction;

    private void Awake()
    {
        mAnimator = GetComponent<tk2dSpriteAnimator>();
        mAnimator.AnimationCompleted = OnAnimationCompleted;
    }

    public void Prepare()
    {
        transform.position = new Vector3(_startingPosition.transform.position.x, _startingPosition.transform.position.y, transform.position.z);
    }

    public void Run(Action onDeliverAction)
    {
        Sound.PlayMailArrivedVoice();

        mOnDeliverAction = onDeliverAction;

        GameobjectPositionAnimation runAnimation = new GameobjectPositionAnimation(new float[] { GameConstants.POSTMAN_TIME_TO_ARRIVE }, 
            new ValueType[] { new Vector3(_endingPosition.transform.position.x, _endingPosition.transform.position.y, transform.position.z) }, 
            new Vector3(_startingPosition.transform.position.x, _startingPosition.transform.position.y, transform.position.z), false);
        runAnimation.AnimationEnded += OnRunAnimationEnded;

        mAnimator.Play(PostmanAnimations.Run.ToString());

        CodeAnimationManager.Instance.ActivateAnimation(runAnimation, new[] { gameObject });
    }

    private void OnRunAnimationEnded(object sender, AbstractCodeAnimation.AnimationEndedEventArgs e)
    {
        mAnimator.Play(PostmanAnimations.Deliver.ToString());
    }

    private void OnAnimationCompleted(tk2dSpriteAnimator animator, tk2dSpriteAnimationClip clip)
    {
        if (clip.name.Equals(PostmanAnimations.Deliver.ToString()))
        {
            mOnDeliverAction();
            mOnDeliverAction = null;
        }
    }
}