using Apewer.Internals;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace Apewer.Source
{

    /// <summary>数据库中的列,类型默认为 NVarChar(255),错误类型将修正为 NText。</summary>
    [Serializable]
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class ColumnAttribute : Attribute
    {

        private PropertyInfo _property = null;

        private string _field = "";
        private int _length = 0;
        private ColumnType _type;

        private bool _independent = false;

        /// <summary>使用自动的列名称。当类型为 VarChar 或 NVarChar 时必须指定长度。</summary>
        /// <exception cref="System.ArgumentException"></exception>
        public ColumnAttribute(ColumnType type = ColumnType.NVarChar255, int length = 0)
        {
            New(null, type, length, true);
        }

        /// <summary>使用指定的列名称。当类型为 VarChar 或 NVarChar 时必须指定长度。</summary>
        /// <exception cref="System.ArgumentException"></exception>
        public ColumnAttribute(string field, ColumnType type = ColumnType.NVarChar255, int length = 0)
        {
            New(field, type, length, false);
        }

        internal ColumnAttribute(string field, ColumnType type, int length, bool underline)
        {
            New(field, type, length, underline);
        }

        /// <summary>属性。</summary>
        public PropertyInfo Property { get { return _property; } internal set { _property = value; } }

        /// <summary>字段名。</summary>
        public string Field { get { return _field; } set { _field = value; } }

        /// <summary>指定字段的最大长度。</summary>
        public int Length { get { return _length; } set { _length = value; } }

        /// <summary>字段类型。</summary>
        public ColumnType Type { get { return _type; } set { _type = value; } }

        /// <summary>Independent 特性。</summary>
        public bool Independent { get { return _independent; } internal set { _independent = value; } }

        /// <exception cref="System.ArgumentException"></exception>
        private void New(string field, ColumnType type, int length, bool underline)
        {
            _field = string.IsNullOrEmpty(field) ? "" : TableStructure.RestrictName(field, underline);
            _type = type;
            switch (type)
            {
                case ColumnType.VarChar:
                case ColumnType.NVarChar:
                    if (length < 1) throw new ArgumentException("最大长度无效。");
                    _length = length;
                    break;
                case ColumnType.VarChar255:
                case ColumnType.NVarChar255:
                    _length = 255;
                    break;
                default:
                    _length = length;
                    break;
            }
        }

    }

}