using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace VCommon.Logging.Viewer.Utility
{
    public static class OperatingFileAssistant
    {
     
        public static async Task<string> ReadTextAsync(FileInfo fileInfo,long seekBeginPosition=0)
        {
            StringBuilder sb = new StringBuilder();
            using (FileStream sourceStream = new FileStream(fileInfo.FullName,
                FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, true))
            {
                sourceStream.Seek(seekBeginPosition, SeekOrigin.Begin);
                byte[] buffer = new byte[4096];
                int numRead;
                while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                {
                    string text = Encoding.UTF8.GetString(buffer, 0, numRead);
                    sb.Append(text);
                }
            }
            return sb.ToString();
        }
        public static async Task<T> ReadTextAsync<T>(FileInfo fileInfo, Func<string, T> readCallBack, long seekBeginPosition = 0) => readCallBack(await ReadTextAsync(fileInfo, seekBeginPosition));
        public static void GetAllFilesByDirectory(string rootPath, List<FileInfo> files, string filePattern = "*.*")
        {
            if (files == null) throw new ArgumentException(nameof(files));

            GetAllFilesByDirectory(new DirectoryInfo(rootPath), files, filePattern);
        }

        private static void GetAllFilesByDirectory(DirectoryInfo rootDirectoryInfo, List<FileInfo> files, string filePattern = "*.*")
        {
            var subPaths = rootDirectoryInfo.GetDirectories();
            foreach (var path in subPaths)
            {
                GetAllFilesByDirectory(path, files, filePattern);
            }

            files.AddRange(rootDirectoryInfo.GetFiles(filePattern));
        }
    }
}