using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;

namespace LJLib
{
    /// <summary>
    /// 文件路径辅助类
    /// </summary>
    internal sealed class FilePathHelper
    {

        private static string _executingfile;
        /// <summary>
        /// 获取当前程序集文件名
        /// </summary>
        /// <returns></returns>
        public static string GetExecutingFile()
        {
            if (string.IsNullOrEmpty(_executingfile))
            {
                _executingfile = Assembly.GetExecutingAssembly().GetName().CodeBase;
                if (_executingfile.StartsWith("file:", StringComparison.OrdinalIgnoreCase))
                {
                    var regex = new Regex("^file:[\\\\/]*", RegexOptions.IgnoreCase);
                    _executingfile = regex.Replace(_executingfile, string.Empty);
                }
            }
            return _executingfile;
        }

        private static string _executingpath;
        /// <summary>
        /// 获取当前程序集路径
        /// </summary>
        /// <returns></returns>
        public static string GetExecutingPath()
        {
            if (string.IsNullOrEmpty(_executingpath))
            {
                _executingpath = Path.GetDirectoryName(GetExecutingFile());
            }
            return _executingpath;
        }
        public static List<FileInfo> GetAllSubFiles(DirectoryInfo dir)
        {
            var rslt = new List<FileInfo>(dir.GetFiles());
            var subDirs = dir.GetDirectories();
            foreach (var subDir in subDirs)
            {
                rslt.AddRange(GetAllSubFiles(subDir));
            }
            return rslt;
        }

        public static void ClearTmpFile(string extname, string excludePath = null)
        {
            var rootPath = GetExecutingPath();
            var rootDir = new DirectoryInfo(rootPath);
            var subfiles = GetAllSubFiles(rootDir);
            foreach (var file in subfiles)
            {
                if (!string.IsNullOrEmpty(excludePath) && file.FullName.StartsWith(excludePath))
                {
                    continue;
                }
                try
                {
                    if (file.Name.EndsWith(extname))
                    {
                        file.Delete();
                    }
                }
                catch (Exception ex)
                {
                    Trace.Write(ex);
                }
            }
        }
    }
}
