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

public class MachineUpgradeView : MonoBehaviour
{
    private static readonly string harvestedTextFormat = "{0}";
    [SerializeField] private Text priceText;
    [SerializeField] private Text currentHarvestedText;
    [SerializeField] private Text nextHarvestedText;
    [SerializeField] private Transform currentMachineImage;
    [SerializeField] private Transform nextMachineImage;
    [SerializeField] private Button dialogButton;
    [SerializeField] private GameObject disableButton;
    [SerializeField] private GameObject maxWindow;
    [SerializeField] private Text maxHarvestedText;
    [SerializeField] private Transform maxMachineImage;

    public IObservable<Unit> ButtonClickObserve => dialogButton.OnClickAsObservable().TakeUntilDestroy(this);

    public void SetData(int level, int price)
    {
        maxWindow.SetActive(false);
        var fieldData = SpreadsheetDataManager.Instance.GetBaseDataList<FieldUpgradeData>(Const.FieldUpgradeDataSheet);
        var machineList = fieldData.Where(data => data.Type == CornFieldUpgradeType.Machine).ToList();
        var currentMachineData = machineList.FirstOrDefault(data => data.level == level);
        var nextMachineData = machineList.FirstOrDefault(data => data.level == level + 1);
        var currentHarvestedCorn = currentMachineData?.harvested ?? 20;
        var nextHarvestedCorn = nextMachineData?.harvested ?? 20;
        currentMachineImage.DestroyAllChildrens();
        nextMachineImage.DestroyAllChildrens();
        Instantiate(currentMachineData.GetIconPrefab(), currentMachineImage);
        Instantiate(nextMachineData.GetIconPrefab(), nextMachineImage);
        priceText.text = price.ToString();
        currentHarvestedText.text = string.Format(harvestedTextFormat, currentHarvestedCorn.ToString());
        nextHarvestedText.text = string.Format(harvestedTextFormat, nextHarvestedCorn.ToString());
    }
    
    public void SetMax(int maxLevel)
    {
        maxWindow.SetActive(true);
        var fieldData = SpreadsheetDataManager.Instance.GetBaseDataList<FieldUpgradeData>(Const.FieldUpgradeDataSheet);
        var machine = fieldData.First(x => x.Type == CornFieldUpgradeType.Machine && x.level == maxLevel);
        maxMachineImage.DestroyAllChildrens();
        Instantiate(machine.GetIconPrefab(), maxMachineImage);
        maxHarvestedText.text = string.Format(harvestedTextFormat, machine.harvested.ToString());
    }

    public void SetButtonActive(bool active)
    {
        dialogButton.gameObject.SetActive(active);
        disableButton.SetActive(!active);
    }
}
