using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Xml;

namespace WebAPIBase.NetCore.BusinessCore
{
    public abstract class AbstractClassBuilder : IClassBuilder
    {
        public AbstractClassBuilder()
        {
        }

        public abstract EntityData BuildClass(string className);

        protected virtual DataTable BuildTable(XmlNode tablenode)
        {
            try
            {
                XmlNodeList xmlNodeList = tablenode.SelectNodes("Column");
                int count = xmlNodeList.Count;
                if (count == 0)
                {
                    throw new ApplicationException("没有定义字段");
                }
                DataTable dataTable = new DataTable(tablenode.SelectSingleNode("Name").InnerText);
                int count2 = tablenode.SelectNodes("Column[IsKey='true']").Count;
                DataColumn[] array = new DataColumn[count2];
                int num = 0;
                for (int i = 0; i < count; i++)
                {
                    DataColumn dataColumn = new DataColumn(xmlNodeList[i].SelectSingleNode("Name").InnerText);
                    string innerText = xmlNodeList[i].SelectSingleNode("DataType").InnerText;
                    dataColumn.DataType = Type.GetType(innerText);
                    if ("System.String" == innerText)
                    {
                        dataColumn.MaxLength = int.Parse(xmlNodeList[i].SelectSingleNode("ColumnSize").InnerText);
                    }
                    if ("true" == xmlNodeList[i].SelectSingleNode("IsKey").InnerText)
                    {
                        array[num] = dataColumn;
                        num++;
                    }
                    dataTable.Columns.Add(dataColumn);
                }
                if (count2 > 0)
                {
                    dataTable.PrimaryKey = array;
                }
                return dataTable;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected virtual XmlNode GetXmlRoot(string className)
        {
            XmlDocument xmlDoc = XmlDefineFileManage.GetXmlDoc(className);
            return xmlDoc.DocumentElement;
        }

        public virtual SqlStruct GetSqlStruct(string className, string sqlStringName)
        {
            return SqlManager.GetSqlStruct(className, className, sqlStringName);
        }
    }
}
