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

namespace Apewer.Web
{

    /// <summary></summary>
    [Serializable]
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class ApiAttribute : Attribute
    {

        private const bool DefaultVisible = true;

        private string _name = "";
        private string _caption = "";
        private bool _visible = DefaultVisible;

        /// <summary></summary>
        public string Name { get { return _name; } }

        /// <summary></summary>
        public string Caption { get { return _caption; } }

        /// <summary></summary>
        public bool Visible { get { return _visible; } }

        private void Initialize(string name = "", string caption = "", bool visible = DefaultVisible)
        {
            _name = string.IsNullOrEmpty(name) ? "" : name.ToLower().Trim();
            _caption = string.IsNullOrEmpty(caption) ? "" : caption.Trim();
            _visible = visible;
        }

        /// <summary></summary>
        public ApiAttribute(string name = null, string caption = null, bool visible = DefaultVisible)
        {
            Initialize(name, caption, visible);
        }

        /// <summary></summary>
        public static string GetName(Type type, bool inherit = true)
        {
            if (type == null) return null;

            var name = null as string;
            var attributes = type.GetCustomAttributes(typeof(ApiAttribute), inherit);
            if (attributes.Length > 0)
            {
                var attribute = attributes[0] as ApiAttribute;
                name = attribute.Name;
            }

            if (string.IsNullOrEmpty(name)) name = type.Name;
            return name;
        }

        /// <summary></summary>
        public static string GetCaption(Type type, bool inherit = true)
        {
            if (type == null) return null;

            var attributes = type.GetCustomAttributes(typeof(ApiAttribute), inherit);
            if (attributes.Length > 0)
            {
                var attribute = attributes[0] as ApiAttribute;
                return attribute.Caption;
            }

            return type.Name;
        }

    }

}