using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public sealed class CommunicationsPanel : MonoBehaviour
{
    public enum Type {
        Trade = 0,
        Service = 1, 
        Yard = 2,
        Info = 3,
        Explore = 4
    }

    [SerializeField]
    private Button tradeButton = null;
    [SerializeField]
    private Button serviceButton = null;
    [SerializeField]
    private Button yardButton = null;
    [SerializeField]
    private Button infoButton = null;
    [SerializeField]
    private Button exploreButton = null;

    private Action<Type> onSelectCommunication = null;
    private Dictionary<Type, Button> buttons = new Dictionary<Type, Button>(4);

    public void ShowVariants(List<Type> activeCommunications, Action<Type> callback = null)
    {
        gameObject.SetActive(true);
        onSelectCommunication = callback;
        HideAllCommunications();
        ShowActiveCommunications(activeCommunications);
    }

    public void Hide()
    {
        onSelectCommunication = null;
        gameObject.SetActive(false);
    }

    private void HideAllCommunications()
    {
        foreach (var button in buttons.Values)
        {
            button.SetActive(false);
        }
    }
    private void ShowActiveCommunications(List<Type> communications)
    {
        if (communications == null)
            return;
        foreach (var communication in communications)
        {
            buttons[communication].SetActive(true);
        }
    }

    public void Awake()
    {
        buttons = new Dictionary<Type, Button>(5);
        AddButton(Type.Trade, tradeButton);
        AddButton(Type.Service, serviceButton);
        AddButton(Type.Yard, yardButton);
        AddButton(Type.Info, infoButton);
        AddButton(Type.Explore, exploreButton);
    }

    private void AddButton(Type type, Button button)
    {
        button.onClick.AddListener(() => onSelectCommunication?.Invoke(type));
        buttons.Add(type, button);
    }

    public void OnDestroy()
    {
        foreach (var button in buttons.Values)
            button.onClick.RemoveAllListeners();
        buttons.Clear();
    }
}
