using System;
using I2.Loc;
using UniRx;
using UnityEngine;
using UnityEngine.UI;

namespace MyGame.Scenes.marketing.Scripts
{
    public class MarketSignBoardView : MonoBehaviour
    {
        [SerializeField] private Text remainTimeText;
        [SerializeField] private GameObject normalBoardObject;
        [SerializeField] private GameObject tastingBoardObject;
        private IDisposable timerDispose;

        // 宣伝中は宣伝優先で通常看板
        public void SetActiveTastingBoard(bool active)
        {
            normalBoardObject.SetActive(!active);
            tastingBoardObject.SetActive(active);
        }
        
        private void SetTime(int seconds)
        {
            seconds = Mathf.Max(0, seconds);
            remainTimeText.text = $"{ScriptLocalization.UI.MarketingTastingRestTime}{Mathf.Min(seconds / 60, 99):D2}：{seconds % 60:D2}";
        }

        public void SetTimer(int remaining, Action onInterval = null, Action onComplete = null)
        {
            timerDispose?.Dispose();
            var timer = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(1f))
                .Select(x => (int)(remaining - x))
                .TakeWhile(x => x >= 0);
            timerDispose = timer.Subscribe(x =>
            {
                SetTime(x);
                onInterval?.Invoke();
            }, () =>
            {
                remainTimeText.text = ScriptLocalization.UI.MarketingTastingTimeUp;
                onComplete?.Invoke();
            }).AddTo(this);
        }

        public void CancelTasting()
        {
            timerDispose?.Dispose();
            remainTimeText.text = ScriptLocalization.UI.MarketingTastingTimeUp;
        }
    }
}