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

namespace MyGame.Scenes.CornField.Scripts
{
    public class FertilizerButtonView : MonoBehaviour
    {
        private static readonly string remainTimeFormat = "{0:D2}:{1:D2}";
        [SerializeField] private Button rewardButton;
        [SerializeField] private GameObject DisableObject;
        [SerializeField] private Text remainTimeText;
        private IDisposable timerDisposable = null;
        public IObservable<Unit> RewardButton => rewardButton.OnClickAsObservable().TakeUntilDestroy(this);

        private void SetButtonActive(bool active)
        {
            rewardButton.gameObject.SetActive(active);
            DisableObject.SetActive(!active);
        }

        private void SetTime(int seconds)
        {
            seconds = Mathf.Max(0, seconds);
            remainTimeText.text = string.Format(remainTimeFormat, seconds / 60, seconds % 60);
        }

        public void ResetTimer(int time)
        {
            timerDisposable?.Dispose();
            SetButtonActive(time <= 0);
            SetTime(time);
            timerDisposable = Observable.Timer(TimeSpan.Zero,TimeSpan.FromSeconds(1f))
                .Select(x => (int)(time - x))
                .TakeWhile(x => x > 0)
                .Subscribe(x =>
                {
                    SetTime(x);
                }, () =>
                {
                    SetButtonActive(true);
                }).AddTo(this);
        }
    }
}