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

public class PanSelector : MonoBehaviour
{
    [SerializeField] private Button prevPanButton;
    [SerializeField] private Button nextPanButton;

    [SerializeField] private Text panName;
    [SerializeField] private Text panText;
    [SerializeField] private Transform panIconTarget;
    public IReadOnlyReactiveProperty<PanData> SelectedPanData => selectedPanData;
    private readonly ReactiveProperty<PanData> selectedPanData = new ReactiveProperty<PanData>();
    private readonly ReactiveProperty<int> selectedIndex = new ReactiveProperty<int>();

    private void Start()
    {
        selectedPanData.AddTo(this);
        selectedIndex.AddTo(this);
        var panList = SpreadsheetDataManager.Instance.GetBaseDataList<PanData>(Const.PanDataSheet);
        var myPanList = panList.Where(data => GameDataManager.GameData.Pans.Contains(data.id)).ToList();
        var panCount = myPanList.Count;
        selectedPanData.Value = myPanList[0];
        selectedPanData.Subscribe(data =>
        {
            SetData(data);
        }).AddTo(this);
        selectedIndex.Subscribe(x =>
        {
            selectedPanData.Value = myPanList[x];
        }).AddTo(this);
        prevPanButton.OnClickAsObservable().Subscribe(_ =>
        {
            selectedIndex.Value = selectedIndex.Value == 0 ? panCount - 1 : selectedIndex.Value - 1;
        }).AddTo(this);
        nextPanButton.OnClickAsObservable().Subscribe(_ =>
        {
            selectedIndex.Value = selectedIndex.Value == panCount - 1 ? 0 : selectedIndex.Value + 1;
        }).AddTo(this);
    }

    private void SetData(PanData data)
    {
        panName.text = data.name;
        panText.text = data.text;
        panIconTarget.DestroyAllChildrens();
        Instantiate(data.GetIconPrefab(), panIconTarget);
    }
}
