using NTDLS.Helpers;

namespace ZelWiki.Engine.Function
{
    public class FunctionParameters
    {
        private readonly FunctionCall _owner;
        public FunctionParameters(FunctionCall owner)
        {
            _owner = owner;
        }

        /// <summary>
        /// 
        /// </summary>
        public List<OrdinalParameter> Ordinals { get; set; } = new();

        /// <summary>
        /// 
        /// </summary>
        public List<NamedParameter> Named { get; private set; } = new();


        
        public T Get<T>(string name)
        {
            try
            {
                var value = Named
                    .FirstOrDefault(o => o.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))?.Value;
                if (value == null)
                {
                    var prototype = _owner.Prototype.Parameters.First(o => o.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
                    return Converters.ConvertTo<T>(prototype.DefaultValue) ??
                           throw new Exception("值不能为空");
                }

                return Converters.ConvertTo<T>(value) ?? throw new Exception("值不能为空");
            }
            catch (Exception ex)
            {
                throw new Exception($"函数 [{_owner.Name}], {ex.Message}");
            }
        }

        public T Get<T>(string name, T defaultValue)
        {
            try
            {
                var value = Named
                    .FirstOrDefault(o => o.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))?.Value;
                if (value == null)
                {
                    return defaultValue;
                }

                return Converters.ConvertTo<T>(value) ?? throw new Exception("值不能为空");
            }
            catch (Exception ex)
            {
                throw new Exception($"函数 [{_owner.Name}], {ex.Message}");
            }
        }

        public List<T> GetList<T>(string name)
        {
            try
            {
                var values = Named.Where(o => o.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))?
                    .Select(o => Converters.ConvertTo<T>(o.Value) ?? throw new Exception("值不能为空"))
                    ?.ToList();

                return values ?? new List<T>();
            }
            catch (Exception ex)
            {
                throw new Exception($"函数 [{_owner.Name}], {ex.Message}");
            }
        }
    }
}