using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using MrWu.Debug;
using Server.Core;

namespace Server
{
    public class TableManager : SingleInstance<TableManager>
    {
        /// <summary>
        /// 配置表版本 改了结构需要版本 + 1
        /// 优化表格 2
        /// 新增比赛赔率 3
        /// 新增排队参数 4
        /// 新增常量表 5
        /// 新版道具系统 配置合并 6
        /// 版本表修改 7
        /// 增加实体兑换商城，修改普通兑换商城配置表
        /// </summary>
        public const string VERSION = "8";

        /// <summary>
        /// 之前的配置表数据
        /// </summary>
        private readonly Dictionary<string, byte[]> tableDatasBak = new Dictionary<string, byte[]>();
        
        /// <summary>
        /// 配置表数据
        /// </summary>
        private readonly Dictionary<string, byte[]> tableDatas = new Dictionary<string, byte[]>();

        public NodeInfo NodeInfo
        {
            get;
            private set;
        }

        private string GetConfigPath()
        {
            return $"C:/ConfigData/{VERSION}";
        }

        public static string GetRobotInfoPath()
        {
            return "C:/ConfigData/names_ts.txt";
        }

        public bool LoadTableData(string configPath = null)
        {
            if (string.IsNullOrEmpty(configPath))
            {
                configPath = GetConfigPath();
            }
            try
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(configPath);
                if (!directoryInfo.Exists)
                {
                    Debug.Error("未找到配置表目录!");
                    return false;
                }
        
                foreach (FileInfo fileInfo in directoryInfo.GetFiles())
                {
                    string fileName = Path.GetFileNameWithoutExtension(fileInfo.Name);
                    byte[] data = File.ReadAllBytes(fileInfo.FullName);
                    tableDatas[fileName] = data;
                }
                
                ServerConfigManager.Instance.RefreshData();
            }
            catch (Exception e)
            {
                Debug.Error($"读取配置表出错:{e.Message} {e.StackTrace}");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 重新加载配置表
        /// </summary>
        /// <returns></returns>
        public void ReLoadTableData()
        {
            tableDatasBak.Clear();
            foreach (var item in tableDatas)
            {
                tableDatasBak.Add(item.Key, item.Value);
            }

            LoadTableData();
        }

        public void RollBack()
        {
            tableDatas.Clear();
            foreach (var item in tableDatasBak)
            {
                tableDatas.Add(item.Key, item.Value);
            }
        }

        public byte[] GetTableData(string tableName)
        {
            tableName = tableName.ToLower();
            byte[] result = null;
            
            Debug.Log($"tableName:{tableName}");
            
            if (tableDatas.ContainsKey(tableName))
            {
                result = tableDatas[tableName];
                tableDatas.Remove(tableName);
            }

            if (result != null)
            {
                Debug.Log("Table is not null!");
            }
            else
            {
                Debug.Log("table is null!" + tableName);
            }

            return result;
        }

        public bool ReadNodeInfo()
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(DirectoryManager.GetNodeConfigPath());
                XmlNode node = doc.SelectSingleNode("NodeInfo");
                NodeInfo nodeInfo = new NodeInfo();
                nodeInfo.Id = byte.Parse(node.SelectSingleNode("Id").InnerText);
                nodeInfo.NodeNum = byte.Parse(node.SelectSingleNode("NodeNum").InnerText);
                NodeInfo = nodeInfo;
            }
            catch (Exception e)
            {
                Debug.Error($"读取节点信息出错! {e.Message}");
                return false;
            }

            return true;
        }
    }
}