using System;
using System.Collections.Generic;
using System.Reflection;

namespace Apewer.Web
{

    internal sealed class ApiFunction
    {

        internal ApiApplication Application;
        internal MethodInfo Method;
        internal Type Returnable;
        internal ParameterInfo[] Parameters;
        internal bool ParamIsRecord = false;

        // 主特性和主要属性。
        // internal ApiAttribute Attribute;
        internal string Name = null;
        internal string Lower = null;

        // 附加特性。
        internal bool Hidden;
        internal string Caption;
        internal string Description;

        private Class<Json> psJson = null;

        internal Json ToJson(ApiOptions options)
        {
            if (Hidden) return null;
            var json = Json.NewObject();
            json.SetProperty("name", Name);
            if (!string.IsNullOrEmpty(Caption)) json.SetProperty("caption", Caption);
            if (!string.IsNullOrEmpty(Description)) json.SetProperty("description", Description);
            if (options.WithParameters)
            {
                if (psJson == null)
                {
                    if (Parameters == null || Parameters.Length < 0)
                    {
                        psJson = new Class<Json>();
                    }
                    else
                    {
                        var ps = Json.NewArray();
                        var psList = new List<ParameterInfo>();
                        psList.AddRange(Parameters);
                        psList.Sort(new Comparison<ParameterInfo>((a, b) => a.Name.CompareTo(b.Name)));
                        foreach (var pi in psList)
                        {
                            var p = Json.NewObject();
                            p.SetProperty("name", pi.Name);
                            p.SetProperty("type", pi.ParameterType.Name);
                            ps.AddItem(p);
                        }
                        psJson = new Class<Json>(ps);
                    }
                }
                if (psJson) json.SetProperty("parameters", psJson.Value);
            }
            return json;
        }

    }

}