using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace XKRS.Common.Model.Helper
{
    public static class StaticHelper
    {


        #region 检测文件状态及操作方式选择
        [DllImport("kernel32.dll")]
        private static extern IntPtr _lopen(string lpPathName, int iReadWrite);
        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(IntPtr hObject);
        private const int OF_READWRITE = 2;
        private const int OF_SHARE_DENY_NONE = 0x40;
        private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
        /// <summary>
        /// 检测文件是否只读或者使用
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns>true可用，false在用或只读</returns>
        public static bool CheckFileCanUse(string fileName)
        {
            if (!File.Exists(fileName))
                return true;//文件不存在
            if ((File.GetAttributes(fileName) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                return false;//文件只读
            IntPtr vHandle = _lopen(fileName, OF_READWRITE | OF_SHARE_DENY_NONE);
            if (vHandle == HFILE_ERROR)
            {
                CloseHandle(vHandle);
                return false;//文件被占用
            }
            CloseHandle(vHandle);//文件没被占用
            return true;
        }


        #endregion

        public static List<FileInfo>GetAllFileByFolder(string folderName,string fileFilter,bool isContainSubFolder = false)
        {
            List<FileInfo> resList = new List<FileInfo>();
            try
            {
                DirectoryInfo currDir = new DirectoryInfo(folderName);//当前目录
                FileInfo[] currFiles = currDir.GetFiles(fileFilter);//当前目录文件
                foreach (FileInfo file in currFiles)
                {
                    if (fileFilter.ToLower().IndexOf(file.Extension.ToLower()) >= 0)
                    {
                        resList.Add(file);
                    }
                }
                if (isContainSubFolder)
                {
                    //GetDirectories:返回指定目录中子目录的名称
                    string[] subFolders = Directory.GetDirectories(folderName);
                    foreach(string subFolder in subFolders)
                    {
                        resList.AddRange(GetAllFileByFolder(subFolder, fileFilter));//递归
                    }
                }

            }
            catch(Exception ex)
            {
                throw ex;
            }
            return resList;
        }

    }
}
