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

namespace MyGame.Scenes.Settings.Scripts
{
    public class SettingDialog : 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 Slider volumeSlider;
        [SerializeField] private Toggle vibrationalToggle;
        [SerializeField] private GameObject soundOnIcon;
        [SerializeField] private GameObject vibeOnIcon;

        private void Start()
        {
            closeButton.OnClickAsObservable().Take(1).Subscribe(_ =>
            {
                SoundManager.Instance.SaveVolumeBGM();
                SoundManager.Instance.SaveVolumeSE();
                VibrationManager.Instance.SaveEnable(vibrationalToggle.isOn);
                transform.parent.SetLocalScale(0);
                backgroundAnimator.SetTrigger(CloseTrigger);
                this.CallWaitForSeconds(.25f, () =>
                {
                    TransitionManager.Instance.UnloadScene(GameScenes.SettingsDialog);
                });
            }).AddTo(this);
            
            volumeSlider.value = SoundManager.Instance.GetVolume(SoundType.BGM);
            volumeSlider.OnValueChangedAsObservable().Subscribe(volume =>
            {
                var currentEnabled = SoundManager.Instance.IsEnabled(SoundType.BGM);
                var newEnabled = !Mathf.Approximately(volume, 0f);
                if (currentEnabled != newEnabled)
                {
                    SoundManager.Instance.EnabledSound(SoundType.BGM, newEnabled);
                    SoundManager.Instance.EnabledSound(SoundType.SE, newEnabled);
                    soundOnIcon.SetActive(newEnabled);
                }
                SoundManager.Instance.ChangeVolume(SoundType.BGM, volume);
                SoundManager.Instance.ChangeVolume(SoundType.SE, volume);
            }).AddTo(this);
            
            vibrationalToggle.OnValueChangedAsObservable().Subscribe(x =>
            {
                if (x)
                {
                    VibrationManager.Instance.PlayVibrationOnce();
                }
                vibeOnIcon.SetActive(x);
            }).AddTo(this);
            vibrationalToggle.isOn = VibrationManager.Instance.IsEnable;
        }
    }
}