using System;
using System.IO;
using GameData;
using MrWu.Debug;

namespace Server
{
    /// <summary>
    /// 文件夹管理
    /// </summary>
    public static class DirectoryManager
    {
        /// <summary>
        /// 数据文件根节点
        /// </summary>
        public const string RootPath = "ServerData";
        
        static DirectoryManager()
        {
            try
            {
                if (!Directory.Exists(RootPath))
                {
                    Directory.CreateDirectory(RootPath);
                }
            }
            catch (Exception e)
            {
                Debug.Error($"Create RootPath Error:{e.Message}");
            }
        }

        public static string GetIconPath()
        {
            string iconPath = "res/icon.ico";
            string fullPath = Path.Combine(RootPath, iconPath);

            if (File.Exists(fullPath))
            {
                return fullPath;
            }

            Debug.Error($"ICON 不在新目录:{fullPath}");
            return iconPath;
        }

        public static string GetNodeConfigPath()
        {
            string nodeConfigPath = "Node.config";
            string fullPath = Path.Combine(RootPath, nodeConfigPath);

            if (File.Exists(fullPath))
            {
                return fullPath;
            }
            
            Debug.Error($"Node.config 不在新目录:{fullPath}");
            return nodeConfigPath;
        }
        
        public static string GetPath(string path)
        {
            string fullPath = Path.Combine(RootPath, path);
            if (Path.HasExtension(fullPath))
            {
                // 获取文件的上级文件夹路径
                string directoryPath = Path.GetDirectoryName(fullPath);
                // 如果上级文件夹不存在，就创建它
                if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }
            }
            else
            {
                // 如果该文件夹不存在，就直接创建它
                if (!Directory.Exists(fullPath))
                {
                    Directory.CreateDirectory(fullPath);
                }
            }
            
            return fullPath;
        }

        /// <summary>
        /// 获取统计库数据
        /// </summary>
        /// <returns></returns>
        public static string GetStaticsDbPath(ModuleUtile module)
        {
            string fullPath = Path.Combine(RootPath, $"gamestatics.{module.id}");
            return fullPath;
        }

        /// <summary>
        /// 获取CDN 黑名单列表保存路径
        /// </summary>
        /// <param name="urlName"></param>
        /// <returns></returns>
        public static string GetCDNIPBlackListPath(string urlName)
        {
            return Path.Combine(RootPath,$"{urlName}_blacklist");
        }
    }
}