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

namespace WebAPIBase.NetCore.BusinessCore
{
    public class StandardTableClassBuilder : AbstractClassBuilder
    {
        public override EntityData BuildClass(string className)
        {
            try
            {
                string name = "";
                EntityData entityData = new EntityData();
                entityData.ClassName = className;
                entityData.EntityTypeName = "Standard";
                XmlNode xmlRoot = GetXmlRoot(className);
                XmlNodeList xmlNodeList = xmlRoot.SelectNodes("Table");
                foreach (XmlNode item in xmlNodeList)
                {
                    string innerText = item.SelectSingleNode("Name").InnerText;
                    XmlNode xmlRoot2 = GetXmlRoot(innerText);
                    XmlNode tablenode = xmlRoot2.SelectSingleNode("Table");
                    entityData.Tables.Add(BuildTable(tablenode));
                    if (item.SelectSingleNode("Type").InnerText == "Main")
                    {
                        entityData.MainTableName = innerText;
                        name = innerText;
                    }
                }
                foreach (XmlNode item2 in xmlNodeList)
                {
                    string innerText2 = item2.SelectSingleNode("Name").InnerText;
                    string innerText3 = item2.SelectSingleNode("Type").InnerText;
                    string text = "";
                    string text2 = "";
                    if ("Child" == innerText3)
                    {
                        text = item2.SelectSingleNode("ParentColumnName").InnerText;
                        text2 = item2.SelectSingleNode("ChildColumnName").InnerText;
                        entityData.Relations.Add(className + "-" + innerText2, entityData.Tables[name].Columns[text], entityData.Tables[innerText2].Columns[text2]);
                    }
                    else if ("Parent" == innerText3)
                    {
                        text = item2.SelectSingleNode("ParentColumnName").InnerText;
                        text2 = item2.SelectSingleNode("ChildColumnName").InnerText;
                        entityData.Relations.Add(innerText2 + "-" + className, entityData.Tables[innerText2].Columns[text], entityData.Tables[name].Columns[text2]);
                    }
                }
                return entityData;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
