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

public class ExtendedDropdown : MonoBehaviour
{
    public bool LoopAround;
    [SerializeField] private TMPro.TMP_Dropdown _dropdown;
    public UnityEvent<int> OnValueChangedEvent;
    public List<TMPro.TMP_Dropdown.OptionData> options => _dropdown.options;
    public KeyCode PreviousKey  = KeyCode.None;
    public KeyCode NextKey      = KeyCode.None;

    private void Update()
    {
        if(Input.GetKeyDown(PreviousKey))
        {
            DropdownPrevious();
        }
        if (Input.GetKeyDown(NextKey))
        {
            DropdownNext();
        }
    }

    public void OnValueChanged(int index)
    {
        OnValueChangedEvent.Invoke(index);
    }

    public void SetValueWithoutNotify(string value)
    {
        var option = options.FindIndex(v => v.text == value);
        SetValueWithoutNotify(option);
    }

    public void SetValueWithoutNotify(int value)
    {
        _dropdown.SetValueWithoutNotify(value);
    }

    public void DropdownPrevious()
    {
        if (LoopAround)
        {
            _dropdown.value = _dropdown.value - 1 < 0 ? _dropdown.options.Count - 1 : _dropdown.value - 1;
        }
        else
        {
            _dropdown.value = Mathf.Clamp(_dropdown.value - 1, 0, _dropdown.options.Count - 1);
        }
    }

    public void DropdownNext()
    {
        if (LoopAround)
        {
            _dropdown.value = _dropdown.value + 1 >= _dropdown.options.Count ? 0 : _dropdown.value + 1;
        }
        else
        {
            _dropdown.value = Mathf.Clamp(_dropdown.value + 1, 0, _dropdown.options.Count - 1);
        }
    }

    public void SetOptions(List<string> values, bool nullValue = false, bool sortValues = false)
    {
        var dd = _dropdown;
        dd.ClearOptions();
        if (nullValue)
            dd.AddOptions(new List<string>() { Strings.NoValueSelectedString });
        if (values != null)
        {
            if (sortValues)
            {
                values = new List<string>(values);
                values.Sort();
            }
            dd.AddOptions(values);
        }
    }
}
