using System;
using System.Collections.Generic;
using System.Text;

namespace Apewer.Run
{

    public class Web
    {

        public Web()
        {
            // GetParameter(Json.Parse("{\"status\":2,\"after\":0,\"before\":0}"), "status");
        }

        string GetParameter(Json data, params string[] names)
        {
            if (names == null || names.Length < 1) return null;

            var sameNames = new List<string>();
            var lowerNames = new List<string>();
            foreach (var name in names)
            {
                if (string.IsNullOrEmpty(name)) continue;
                sameNames.Add(name);

                var lower = TextUtility.ToLower(name);
                if (string.IsNullOrEmpty(lower)) continue;
                lowerNames.Add(lower);
            }

            // POST 优先。
            if (data != null && data.IsObject)
            {
                var properties = data.GetProperties();
                if (properties != null)
                {
                    // Json 区分大小写,先全字匹配。
                    foreach (var property in properties)
                    {
                        if (!property.IsProperty) continue;
                        if (sameNames.Contains(property.Name) && property.Value != null)
                        {
                            var value = property.Value;
                            if (value == null) continue;
                            var text = value.ToString();
                            if (!string.IsNullOrEmpty(text)) return text;
                        }
                    }

                    // 以小写模糊匹配。
                    foreach (var property in properties)
                    {
                        if (!property.IsProperty) continue;
                        var lowerName = TextUtility.ToLower(property.Name);
                        if (lowerNames.Contains(lowerName) && property.Value != null)
                        {
                            var value = property.Value;
                            if (value == null) continue;
                            var text = value.ToString();
                            if (!string.IsNullOrEmpty(text)) return text;
                        }
                    }
                }
            }

#if NETFX
            // NETFX 最后搜索 GET 参数。
            if (request.Url != null)
            {
                var value = GetParameter(request.Url, names);
                if (!string.IsNullOrEmpty(value)) return value;
            }
#endif

            return null;
        }

    }

}