using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using SystemX.Net.Platform.Common.Util;

namespace SystemX.PLC.Model
{
    public class ModelSetupTemplate
    {
        public class ModelElementData
        {
            public ModelElementData() { }
            public ModelElementData(ModelElementData model)
            {
                Name = model.Name;
                DataType = model.DataType;
                Desc = model.Desc;
                Value = model.Value;
                IsIDKey = model.IsIDKey;

                ChangeType();
            }
            string InternalValue { get; set; } = string.Empty;
            public string Name { get; set; } = string.Empty;
            public string DataType { get; set; } = string.Empty;
            public string Desc { get; set; } = string.Empty;
            public string Value
            {
                get { return InternalValue; }
                set
                {
                    string strChangineValue = value;
                    Type tResult = CommonUtil.GetType(DataType);

                    if (tResult == typeof(System.Boolean) && !string.IsNullOrWhiteSpace(Value))
                    {
                        int nValue = strChangineValue == true.ToString() ? 1 : 0;

                        InternalValue = nValue.ToString();
                    }
                    else
                        InternalValue = strChangineValue;
                }
            }
            public object RValue { get { ChangeType(); return objConvertedValue; } }
            object objConvertedValue = null;
            public bool IsIDKey { get; set; } = false;

            void ChangeType()
            {
                try
                {
                    Type tResult = CommonUtil.GetType(DataType);
                    string strChangineValue = Value;

                    if (string.IsNullOrEmpty(strChangineValue) && tResult != typeof(System.Boolean))
                        return;

                    if (tResult == typeof(System.Boolean))
                    {
                        if (!string.IsNullOrWhiteSpace(Value))
                        {
                            bool bValue = false;
                            int nValue = 0;

                            if (Boolean.TryParse(Value, out bValue))
                                strChangineValue = bValue.ToString();
                            else if (Int32.TryParse(Value, out nValue))
                                strChangineValue = nValue == 0 ? false.ToString() : true.ToString();
                        }
                        else
                            strChangineValue = false.ToString();
                    }

                    objConvertedValue = Convert.ChangeType(strChangineValue, tResult);
                }
                catch (Exception ex)
                {
                    LogMessage.MessageOutput.ConsoleWrite($"Converting Error on <{Name}>, Value: {Value}. \n - Error Message: {ex.Message}", ConsoleColor.Red, LogMessage.LogMessageLevel.FATAL);
                }
            }
        }

        public Dictionary<string, ModelElementData> ModelDescriptionDictionary { get; set; }
        public Dictionary<string, ModelElementData> ModelDataDictionary { get; set; }

        public ModelSetupTemplate(ModelSetupTemplate model)
        {
            ModelDescriptionDictionary = CloneDictionary(model.ModelDescriptionDictionary);
            ModelDataDictionary = CloneDictionary(model.ModelDataDictionary);
        }

        public ModelSetupTemplate(string strTemplatePath)
        {
            ModelDescriptionDictionary = new Dictionary<string, ModelElementData>();
            ModelDataDictionary = new Dictionary<string, ModelElementData>();

            LoadXmlConfig(strTemplatePath);
        }

        public ModelElementData GetPrimaryKey()
        {
            List<ModelElementData> vModelelemdata = ModelDataDictionary.Values.Where(x => x.IsIDKey == true).ToList();

            return vModelelemdata.Count > 0 ? vModelelemdata[0] : null;
        }

        public ModelElementData FindKey(string strName)
        {
            return ModelDataDictionary[strName];
        }

        public string GetSaveModelColName()
        {
            string strResult = string.Empty;

            foreach (ModelElementData element in ModelDataDictionary.Values)
                strResult += element.Name + ModelTemplateDefinition.ModelFileDelimiter;

            strResult = strResult.Remove((strResult.Length - 1), 1);

            return strResult;
        }

        public string GetSaveModelValue()
        {
            string strResult = string.Empty;

            foreach (ModelElementData element in ModelDataDictionary.Values)
                strResult += element.Value + ModelTemplateDefinition.ModelFileDelimiter;

            strResult = strResult.Remove((strResult.Length - 1), 1);

            return strResult;
        }

        #region Initialization
        void LoadXmlConfig(string strXmlPath)
        {
            if (!File.Exists(strXmlPath))
                return;

            XDocument xDoc = XDocument.Load(strXmlPath);

            var xElement = xDoc.Element(ModelTemplateDefinition.ModelRoot);

            if (xElement == null) return;

            var xelemDescRoot = xElement.Element(ModelTemplateDefinition.DescriptionRoot);
            var xelemDSRoot = xElement.Element(ModelTemplateDefinition.DSRoot);

            LoadXmlDataForTemplate(xelemDescRoot, ModelDescriptionDictionary);
            LoadXmlDataForTemplate(xelemDSRoot, ModelDataDictionary);
        }

        public void LoadXmlDataForTemplate(XElement xElemRoot, Dictionary<string, ModelElementData> dicResult)
        {
            foreach (XElement elem in xElemRoot.Elements())
            {
                if (elem.Name != ModelTemplateDefinition.Element)
                    continue;

                string strName = string.Empty;
                string strDataType = string.Empty;
                string strDesc = string.Empty;
                string strValue = elem.Value;
                bool bIDKey = strValue == ModelTemplateDefinition.IDKeyMark ? true : false;

                GetAttributes(elem, ref strName, ref strDataType, ref strDesc);
                dicResult.Add(strName, new ModelElementData() { Name = strName, DataType = strDataType, Desc = strDesc, IsIDKey = bIDKey });
            }

            if (GetPrimaryKey() == null)
                dicResult[dicResult.Keys.ElementAt(0)].IsIDKey = true;
        }

        void GetAttributes(XElement xElem, ref string strName, ref string strType, ref string strDesc)
        {
            strName = string.Empty;
            strType = string.Empty;
            strDesc = string.Empty;

            foreach (XAttribute xattrb in xElem.Attributes())
            {
                if (xattrb.Name == ModelTemplateDefinition.AttrbName)
                    strName = xattrb.Value;
                else if (xattrb.Name == ModelTemplateDefinition.AttrbDataType)
                    strType = xattrb.Value;
                else if (xattrb.Name == ModelTemplateDefinition.AttrbDesc)
                    strDesc = xattrb.Value;
            }
        }

        public ModelSetupTemplate GetNewModelStructure()
        {
            ModelSetupTemplate model = new ModelSetupTemplate(this);

            return model;
        }

        Dictionary<string, ModelElementData> CloneDictionary(Dictionary<string, ModelElementData> dicOrg)
        {
            Dictionary<string, ModelElementData> dicClone = new Dictionary<string, ModelElementData>();

            foreach (string strKey in dicOrg.Keys)
            {
                ModelElementData modeldata = new ModelElementData(dicOrg[strKey]);

                dicClone.Add(strKey, modeldata);
            }

            return dicClone;
        }
        #endregion
    }
}
