using System;
using UnityEngine;
using UnityEngine.UI;

public sealed class ResourceTradeControlItem : MonoBehaviour
{
    public interface IController {
        void Buy(string id);
        void BuyMax(string id);
        void Sell(string id);
        void SellMax(string id);
    }

    [SerializeField]
    private Text resourceName = null;
    [SerializeField]
    private Text stantionStock = null;
    [SerializeField]
    private Text shipStock = null;
    [SerializeField]
    private Text buyCostLabel = null;
    [SerializeField]
    private Text sellCostLabel = null;
    [SerializeField]
    private Button buyMaxButton = null;
    [SerializeField]
    private Button buyButton = null;
    [SerializeField]
    private Button sellMaxButton = null;
    [SerializeField]
    private Button sellButton = null;

    private string ResourceId { get; set; }
    private IController controller = null;

    public void SetResource(string resourceId, int stockCount, int playerCount, int lastBuyCost, int buyCost, int sellCost)
    {
        ResourceId = resourceId;
        resourceName.text = resourceId; // todo make locale
        stantionStock.text = stockCount.ToString();
        shipStock.text = playerCount.ToString() + ((lastBuyCost == 0) ? string.Empty : $" ({lastBuyCost})");
        buyCostLabel.text = buyCost.ToString();
        sellCostLabel.text = sellCost.ToString();
    }

    public void Init(IController purchaseController)
    {
        controller = purchaseController;
    }

    private void Sell()
    {
        controller?.Sell(ResourceId);
    }

    private void SellMax()
    {
        controller?.SellMax(ResourceId);
    }

    private void Buy()
    {
        controller?.Buy(ResourceId);
    }

    internal void SetResource(string resourceId, object p, int v1, int v2, object buyCost, object sellCost)
    {
        throw new NotImplementedException();
    }

    private void BuyMax()
    {
        controller?.BuyMax(ResourceId);
    }

    public void Start()
    {
        buyMaxButton.onClick.AddListener(BuyMax);
        buyButton.onClick.AddListener(Buy);
        sellMaxButton.onClick.AddListener(SellMax);
        sellButton.onClick.AddListener(Sell);
    }

    public void OnDestroy()
    {
        buyMaxButton.onClick.RemoveListener(BuyMax);
        buyButton.onClick.RemoveListener(Buy);
        sellMaxButton.onClick.RemoveListener(SellMax);
        sellButton.onClick.RemoveListener(Sell);
    }
}
