using System;
using UniRx;
using UnityEngine;
using UnityEngine.UI;

namespace MyGame.Scenes.Settings.Scripts
{
    public class HowToPlayWindow : MonoBehaviour
    {
        private static readonly int OpenTrigger = Animator.StringToHash("OpenTrigger");
        private static readonly int CloseTrigger = Animator.StringToHash("CloseTrigger");
        [SerializeField] private Animator backgroundAnimator;
        [SerializeField] private Button closeButton;
        
        [SerializeField] private Button nextButton;
        [SerializeField] private Button prevButton;
        [SerializeField] private GameObject[] explainObjects;

        private void Start()
        {
            closeButton.OnClickAsObservable().Take(1).Subscribe(_ =>
            {
                transform.parent.SetLocalScale(0);
                backgroundAnimator.SetTrigger(CloseTrigger);
                this.CallWaitForSeconds(.25f, () =>
                {
                    TransitionManager.Instance.UnloadScene(GameScenes.HowToPlay);
                });
            }).AddTo(this);

            var objectsLength = explainObjects.Length;
            nextButton.OnClickAsObservable()
                .Select(_ => 1)
                .Merge(prevButton.OnClickAsObservable().Select(_ => -1))
                .Scan(0, (acc, current) => (acc + current + objectsLength) % objectsLength)
                .Subscribe(x =>
                {
                    for (int i = 0; i < objectsLength; i++)
                    {
                        explainObjects[i].SetActive(i == x);
                    }
                }).AddTo(this);
        }
    }
}