using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using Infrastructure;
using SqlSugar;

namespace OpenAuth.App
{
    public class DbExtension
    {
        private ISqlSugarClient _context;

        public DbExtension(ISqlSugarClient context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取数据库一个表的所有属性值及属性描述
        /// </summary>
        /// <param name="moduleName">模块名称/表名</param>
        /// <returns></returns>
        public List<KeyDescription> GetProperties(Type type)
        {
            var result = new List<KeyDescription>();

            var entity = _context.EntityMaintenance.GetEntityInfo(type);

            foreach (var column in entity.Columns)
            {
                object[] objs = column.PropertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
                var description = objs.Length > 0 ? ((DescriptionAttribute)objs[0]).Description : column.ColumnDescription;
                if (string.IsNullOrEmpty(description)) description = column.DbColumnName;

                object[] browsableObjs = column.PropertyInfo.GetCustomAttributes(typeof(BrowsableAttribute), true);
                bool browsable = browsableObjs == null || browsableObjs.Length == 0 ||
                             ((BrowsableAttribute)browsableObjs[0]).Browsable;

                result.Add(new KeyDescription
                {
                    Key = column.DbColumnName,
                    Description = description,
                    Browsable = browsable,
                    Type = column.PropertyInfo.PropertyType.Name
                });
            }
            return result;
        }
    }
}