using System;
using UniRx;
using UniRx.Triggers;
using UnityEngine;

public class BrotherFertilizerAnimation : MonoBehaviour
{
    private static readonly int Walk = Animator.StringToHash("Walk");
    private static readonly int Farming = Animator.StringToHash("Farming");
    [SerializeField] private Animator pinkBrotherAnimator;
    [SerializeField] private Animator blueBrotherAnimator;
    [SerializeField] private Transform pinkFarmingTarget;
    [SerializeField] private Transform pinkWalkEndTarget;
    [SerializeField] private Transform blueFarmingTarget;
    [SerializeField] private Transform blueWalkEndTarget;
    [SerializeField] private float walkSpeed = .5f;

    private readonly CompositeDisposable compositeDisposable = new CompositeDisposable();

    private void Start()
    {
        compositeDisposable.AddTo(this);
        SetActive(false);
    }

    private void SetActive(bool active)
    {
        pinkBrotherAnimator.transform.SetLocalScale(active ? 1 : 0);
        blueBrotherAnimator.transform.SetLocalScale(active ? 1 : 0);
    }

    public void StartAnimation()
    {
        compositeDisposable.Clear();
        SetActive(true);
        pinkBrotherAnimator.SetTrigger(Farming);
        blueBrotherAnimator.SetTrigger(Farming);
        pinkBrotherAnimator.transform.localPosition = pinkFarmingTarget.localPosition;
        blueBrotherAnimator.transform.localPosition = blueFarmingTarget.localPosition;
        pinkBrotherAnimator.transform.localRotation = Quaternion.Euler(Vector3.zero);
        blueBrotherAnimator.transform.localRotation = Quaternion.Euler(Vector3.up * 180);
        
    }

    public void EndAnimation()
    {
        compositeDisposable.Clear();
        // 左右に帰る
        pinkBrotherAnimator.SetTrigger(Walk);
        blueBrotherAnimator.SetTrigger(Walk);
        var pinkTransform = pinkBrotherAnimator.transform;
        var blueTransform = blueBrotherAnimator.transform;
        pinkTransform.localRotation = Quaternion.Euler(Vector3.up * 180);
        blueTransform.localRotation = Quaternion.Euler(Vector3.zero);
        this.UpdateAsObservable().Subscribe(_ =>
        {
            pinkTransform.localPosition = Vector3.MoveTowards(pinkTransform.localPosition,
                pinkWalkEndTarget.localPosition, walkSpeed * Time.deltaTime);
            blueTransform.localPosition = Vector3.MoveTowards(blueTransform.localPosition,
                blueWalkEndTarget.localPosition, walkSpeed * Time.deltaTime);
        }).AddTo(compositeDisposable);
    }
}
