using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Performance.Infrastructure
{
    public static partial class UtilExtensions
    {
        /// <summary>
        /// 获取键值对指定key值，并进行类型转换
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="keyValues"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetValue<T>(this Dictionary<string, object> keyValues, string key, T defaultValue = default(T))
        {
            object value;
            if (keyValues.TryGetValue(key, out value))
                return ConvertHelper.To<T>(value, defaultValue);
            return defaultValue;
        }

        /// <summary>
        /// 获取键值对指定key值，并进行类型转换
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="keyValues"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetValue<T>(this SortedDictionary<string, object> keyValues, string key, T defaultValue = default(T))
        {
            object value;
            if (keyValues.TryGetValue(key, out value))
                return ConvertHelper.To<T>(value, defaultValue);
            return defaultValue;
        }

        /// <summary>
        /// form 转换 键值对
        /// </summary>
        /// <param name="pairs"></param>
        /// <returns></returns>
        public static SortedDictionary<string, object> ToDictionary(this IFormCollection pairs)
        {
            SortedDictionary<string, object> kv = new SortedDictionary<string, object>();
            if (pairs == null || pairs.Keys.Count == 0)
                return kv;
            foreach (var item in pairs.Keys)
            {
                kv.Add(item, pairs[item].FirstOrDefault());
            }
            return kv;
        }
    }
}
