using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using XRTool.Util;
/// <summary>
/// 一个xml编辑器
/// </summary>
namespace PublicTools.XMLDataBase
{
    /// <summary>
    /// 针对某个xml文件进行编辑的类
    /// </summary>
    public class XMLDataEditor : TableInterface
    {
        private XmlDocument xmlDoc;                //可操作的xml文档
        private XmlNode xmlRootNode;              //根节点
        /// <summary>
        /// 文件的绝对路径
        /// </summary>
        private string filePath;
        /// <summary>
        /// 表格的名称
        /// </summary>
        private string tableName;
        /// <summary>
        /// 根节点的名称
        /// </summary>
        /// <summary>
        /// 以绝对路径创建一个对象
        /// </summary>
        /// <param name="filePath"></param>
        public XMLDataEditor(string filePath)
        {
            this.filePath = filePath;
        }

        public XMLDataEditor()
        {
        }
        public bool Open()
        {
            return Open(filePath);
        }
        /// <summary>
        /// 打开xml表格
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public bool Open(string path)
        {
            if (xmlDoc != null && !string.IsNullOrEmpty(this.filePath))
            {
                return true;
            }
            ///开启之前先关闭
            //Close();
            if (File.Exists(path))
            {
                xmlDoc = new XmlDocument();
                tableName = Path.GetFileNameWithoutExtension(path);
                try
                {
                    xmlDoc.Load(path);
                    xmlRootNode = xmlDoc.SelectSingleNode(tableName);
                    return xmlRootNode != null;
                }
                catch (Exception ex)
                {
                    UnityLog.LogError(path + ex.ToString());
                }
            }
            return false;
        }
        public void Close()
        {
            if (xmlDoc != null && !string.IsNullOrEmpty(filePath))
            {
                try
                {
                    xmlDoc.Save(filePath);
                    xmlDoc = null;
                    //filePath = null;
                }
                catch (Exception ex)
                {
                    UnityLog.LogError(filePath + "\n" + ex.ToString());
                }
            }
        }

        public bool InsertData<T>(T data, string priKey)
        {
            Dictionary<string, string> field = ClazzFactory.ClazzAnalyze(data);
            if (field != null && field.Count > 0)
            {
                XmlNode table = xmlRootNode;
                if (string.IsNullOrEmpty(priKey))
                {
                    foreach (var item in field)
                    {
                        priKey = item.Value;
                        break;
                    }
                }
                return InsertData<T>(data, table, field, priKey);
            }
            return false;
        }
        /// <summary>
        /// 插入数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <param name="field"></param>
        private bool InsertData<T>(T data, XmlNode table, Dictionary<string, string> field, string priKey)
        {
            try
            {
                if (string.IsNullOrEmpty(priKey) || priKey == "null")
                {
                    return false;
                }
                if (table.SelectSingleNode(priKey) != null)
                {
                    return UpdateData<T>(data, table, field, priKey);
                }
                ///添加一条数据
                ///按照key值添加一个节点元素
                XmlElement element = xmlDoc.CreateElement(priKey);
                ///循环遍历变量集合，将类的数据集合起来添加
                foreach (var item in field)
                {
                    XmlAttribute xa = xmlDoc.CreateAttribute(item.Key);
                    xa.Value = item.Value;
                    element.Attributes.Append(xa);
                }
                table.AppendChild(element);
                return true;
            }
            catch (Exception ex)
            {
                UnityLog.LogError(data + "  " + priKey + ex.ToString());
                Close();
            }
            return false;
        }
        public bool InsertData<T>(T data)
        {
            return InsertData<T>(data, null);
        }
        /// <summary>
        /// 尝试获取xml的一个表，如果此xml没有此表，则创建一个
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public XmlNode TryGetTable(string tableName)
        {
            XmlNode node = xmlRootNode.SelectSingleNode(tableName);
            if (node != null)
            {
                return node;
            }
            return CreateTable(tableName);
        }


        /// <summary>
        /// 创建一个子节点
        /// </summary>
        /// <param name="tableName"></param>
        public XmlNode CreateTable(string tableName)
        {
            XmlNode table = xmlDoc.CreateElement(tableName);
            xmlRootNode.AppendChild(table);
            Save();
            return table;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="priKey"></param>
        /// <returns></returns>
        public T FindData<T>(string priKey)
        {
            T t = default(T);
            XmlNode table = xmlRootNode;
            try
            {
                XmlNode obj = table.SelectSingleNode(priKey);
                if (obj != null)
                {
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    for (int i = 0; i < obj.Attributes.Count; i++)
                    {
                        dic.Add(obj.Attributes[i].LocalName, obj.Attributes[i].Value);
                    }
                    t = ClazzFactory.ClazzPack<T>(dic);
                }
            }
            catch (Exception ex)
            {
                Close();
                UnityLog.LogError(priKey + ex.ToString());
            }
            return t;
        }

        public List<T> FindAllData<T>()
        {
            XmlNode table = xmlRootNode;

            if (table == null || table.ChildNodes.Count == 0)
            {
                return null;
            }
            List<T> list = new List<T>();

            for (int i = 0; i < table.ChildNodes.Count; i++)
            {//遍历表的子节点
                Dictionary<string, string> values = new Dictionary<string, string>();
                for (int j = 0; j < table.ChildNodes[i].Attributes.Count; j++)
                {
                    values.Add(table.ChildNodes[i].Attributes[j].LocalName, table.ChildNodes[i].Attributes[j].Value);
                }
                list.Add(ClazzFactory.ClazzPack<T>(values));
            }
            return list;
        }
        public List<T> FindAllData<T>(string data)
        {
            return null;
        }
        /// <summary>
        /// 查找所有对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public List<T> FindAllData<T>(byte[] data)
        {
            try
            {
                xmlDoc = new XmlDocument();
                string xmlStr = UnityUtil.GetUTF8String(data);
                xmlDoc.LoadXml(xmlStr);
                tableName = typeof(T).Name;
                xmlRootNode = xmlDoc.SelectSingleNode(tableName);
            }
            catch (Exception ex)
            {
                UnityLog.LogError(ex.ToString());
            }
            return FindAllData<T>();
        }
        public bool UpdateData<T>(T data, string priKey)
        {
            Dictionary<string, string> field = ClazzFactory.ClazzAnalyze(data);
            if (field != null && field.Count > 0)
            {
                XmlNode table = xmlRootNode;
                if (string.IsNullOrEmpty(priKey))
                {
                    foreach (var item in field)
                    {
                        priKey = item.Value;
                        break;
                    }
                }
                return UpdateData<T>(data, table, field, priKey);
            }
            return false;
        }
        private bool UpdateData<T>(T data, XmlNode table, Dictionary<string, string> field, string priKey)
        {
            try
            {
                XmlNode obj = table.SelectSingleNode(priKey);
                if (obj == null)
                {
                    //待更新数据不存在，更新失败
                    return false;
                }

                ///需要判断变量名是否发生了变化
                bool isChanged = false;
                if (obj.Attributes.Count != field.Count)
                {
                    isChanged = true;
                }
                if (!isChanged)
                {
                    int index = 0;
                    foreach (var item in field)
                    {
                        ///变量名不一致
                        if (obj.Attributes[index].LocalName != item.Key)
                        {
                            isChanged = true;
                            break;
                        }
                        index++;
                    }
                }
                if (isChanged)
                {
                    if (DeleteData<T>(priKey))
                    {
                        return InsertData(data, priKey);
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    foreach (var item in field)
                    {
                        if (obj.Attributes[item.Key].Value != item.Value)
                        {
                            obj.Attributes[item.Key].Value = item.Value;
                            isChanged = true;
                        }
                    }
                }
                return isChanged;
            }
            catch (Exception ex)
            {
                UnityLog.LogError(data + "  " + priKey + ex.ToString());
                Close();
            }
            return false;
        }
        public bool UpdateData<T>(T data)
        {
            return UpdateData<T>(data, null);
        }

        public bool DeleteData<T>(string key)
        {
            XmlNode table = xmlRootNode;
            try
            {
                XmlNode obj = table.SelectSingleNode(key);//按照key值确定元素对象
                if (obj == null)
                {
                    return false;
                }
                obj.RemoveAll();
                table.RemoveChild(obj);
                return true;

            }
            catch (Exception ex)
            {
                UnityLog.LogError(ex.ToString());
            }
            return false;
        }

        public bool DeleteAllData<T>()
        {
            try
            {
                XmlNode table = xmlRootNode;
                table.RemoveAll();
                return true;
            }
            catch (Exception ex)
            {
                UnityLog.LogError(ex.ToString());
            }
            return false;
        }

        /// <summary>
        /// 建表
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public bool Create(string tableName)
        {
            try
            {
                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
                if (xmlDoc == null)
                {
                    xmlDoc = new XmlDocument();
                }
                this.tableName = Path.GetFileNameWithoutExtension(tableName);
                XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                xmlRootNode = xmlDoc.CreateElement(this.tableName);
                xmlDoc.AppendChild(xmlDeclaration);
                xmlDoc.AppendChild(xmlRootNode);
                fs.Dispose();
                fs.Close();
                return xmlRootNode != null;
            }
            catch (Exception ex)
            {
                UnityLog.Log("Create Error" + this.tableName + ex.ToString());
            }
            return false;
        }

        public void Save()
        {
            if (xmlDoc != null && !string.IsNullOrEmpty(filePath))
            {
                try
                {
                    xmlDoc.Save(filePath);
                }
                catch (Exception ex)
                {
                    UnityLog.LogError(filePath + "\n" + ex.ToString());
                }
            }
        }


    }
}