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

namespace NBF.Setting
{
    public interface IMultiOption : IOptionBase
    {
        List<string> GetOptionNames();
        bool IsDropdown { get; }
    }

    public abstract class MultiOption<T> : OptionBase, IMultiOption
    {
        protected OptionTable<T> OptionTable = new OptionTable<T>();


        protected void AddOption(string name, T value)
        {
            OptionTable.Add(name, value);
        }

        public List<string> GetOptionNames() => OptionTable.GetNames();

        public virtual bool IsDropdown => false;


        protected void SelectOption(T value, int defaultIndex = 0)
        {
            SetValue(TryGetIndex(value, out var index) ? index : defaultIndex);
        }

        protected void SelectOption(Predicate<T> predicate, int defaultIndex = 0)
        {
            SetValue(TryGetIndex(predicate, out var index) ? index : defaultIndex);
        }

        protected bool TryGetIndex(T option, out int index)
        {
            return TryGetIndex(entry => entry.Equals(option), out index);
        }

        protected bool TryGetIndex(Predicate<T> predicate, out int index)
        {
            index = -1;

            var entries = OptionTable.GetValues();

            for (var i = 0; i < entries.Count; i++)
            {
                if (!predicate(entries[i])) continue;
                index = i;
                return true;
            }

            return false;
        }

        public T GetSelectedOption() => OptionTable.GetValue(Value);

        public override string GetDisplayString()
        {
            return OptionTable.GetName(Value);
        }
    }
}