using R3;
using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace R3
{
    public static class UnityUIBindings
    {
        public static IDisposable SubscribeToScrollbar(this ReactiveProperty<float> source, Scrollbar scrollbar)
        {
            return source.Subscribe(scrollbar, static (x, s) => s.value = x);
        }
        public static IDisposable SubscribeToInputField(this ReactiveProperty<float> source, InputField inputField)
        {
            return source.Subscribe(inputField, static (x, t) => t.text = x.ToString());
        }
        public static IDisposable BindToScrollbar(this ReactiveProperty<float> source, Scrollbar scrollbar)
        {
            var disposable = new CompositeDisposable();

            // 值 → Scrollbar
            source.SubscribeToScrollbar(scrollbar).AddTo(disposable);

            // Scrollbar → 值
            scrollbar.OnValueChangedAsObservable().Subscribe(_value => { source.Value = _value; }).AddTo(disposable);

            return disposable;
        }
        public static IDisposable BindToInputField(this ReactiveProperty<float> source, InputField inputField)
        {
            var disposable = new CompositeDisposable();

            // 值 → InputField
            source.SubscribeToInputField(inputField).AddTo(disposable);

            // InputField → 值
            inputField.OnValueChangedAsObservable().Subscribe(_value => 
            {
                float result;
                if (float.TryParse(_value,out result))
                source.Value = result; 
            }).AddTo(disposable);

            return disposable;
        }
    }
}


