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

public class Choice
{
    public Choice(string text, AudioSource a1 = null, AudioSource a2= null)
    {
        choice = text;
        audio1 = a1;
        audio2 = a2;
    }
    public string choice;
    public AudioSource audio1;
    public AudioSource audio2;
}

public class OptionScreen: MonoBehaviour {
    private static OptionScreen _active = null;
    private List<Choice> _choices = new List<Choice>();
    private List<Button> _buttons = new List<Button>();
    private int _selected = -1;
    public UnityAction<int> callback = null;
    private void Awake()
    {
        foreach(Button button in GetComponentsInChildren<Button>(true))
        {
            _buttons.Add(button);
        }
        gameObject.SetActive(false);
    }
    private void OnDestroy()
    {
        _active = null;
    }
    public void OnSelected(int choice)
    {
        _selected = choice;
        Hide();
    }
    public void Show()
    {
        if(_active != null)
        {
            _active.Hide();
        }
        _active = this;
        _selected = -1;
        for(int i = 0; i<_buttons.Count; ++i)
        {
            Button button = _buttons[i];
            if (i < _choices.Count)
            {
                button.GetComponentInChildren<Text>().text = _choices[i].choice;
            }
            else
            {
                button.gameObject.SetActive(false);
            }
        }
        gameObject.SetActive(true);
        Animator anim = GetComponent<Animator>();
        anim.Play("Base Layer.FADE_IN");
    }
    public void Hide()
    {
        if(_active == this)
        {
            _active = null;
        }
        GetComponent<Animator>().Play("Base Layer.FADE_OUT");
    }
    public void AfterFadeOut()
    {
        if(_selected>=0 && callback != null)
        {
            callback.Invoke(_selected);
        }
        Clear();
        gameObject.SetActive(false);
    }
    public void Clear()
    {
        _selected = -1;
        _choices.Clear();
    }
    public void Add(Choice choice, int index=-1)
    {
        if (index == -1)
            _choices.Add(choice);
        else
            _choices[index] = choice;
    }
    public void Add(string text)
    {
        _choices.Add(new Choice(text));
    }
}
