using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Nirvana.Common
{
    public class FileHelper
    {

        public static IWebHostEnvironment _hostingEnvironment;
        public FileHelper(IWebHostEnvironment environment)
        {
            _hostingEnvironment = environment;
        }

        /// <summary>
        /// 获取文件的绝对路径,针对window程序和web程序都可使用
        /// </summary>
        /// <param name="relativePath">相对路径地址</param>
        /// <returns></returns>
        public static string GetAbsolutePath(string relativePath)
        {
            if (string.IsNullOrEmpty(relativePath))
            {
                throw new ArgumentNullException("参数relativePath空异常！");
            }
            relativePath = relativePath.Replace("/", "\\");
            if (relativePath[0] == '\\')
            {
                relativePath = relativePath.Remove(0, 1);
            }
            //判断是Web程序还是window程序
            if (_hostingEnvironment != null)
            {
                return Path.Combine(_hostingEnvironment.WebRootPath, relativePath);
            }
            else
            {
                return Path.Combine(AppContext.BaseDirectory, relativePath);
            }
        }

        #region 检测指定目录是否存在
        /// <summary>
        /// 检测指定目录是否存在
        /// </summary>
        /// <param name="directoryPath">目录的绝对路径</param>
        /// <returns></returns>
        public static bool IsExistDirectory(string directoryPath)
        {
            return Directory.Exists(directoryPath);
        }
        #endregion

        #region 删除文件
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="file">要删除的文件路径和名称</param>
        public static void DeleteFile(string file)
        {
            if (System.IO.File.Exists(file))
            {
                System.IO.File.Delete(file);
            }
        }

        public static FileStream GetFileStream(string fileName)
        {
            FileStream fileStream = null;
            if (!string.IsNullOrEmpty(fileName) && System.IO.File.Exists(fileName))
            {
                fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            }
            return fileStream;
        }
        #endregion

        /// <summary>
        /// 读取文件（默认编码）
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static string Read(string path)
        {
            return Reads(path);
        }
        /// <summary>
        /// 读取文件,指定编码
        /// </summary>
        /// <param name="path"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string Reads(string path,Encoding encode=null)
        {
            if(encode == null)
            {
                encode = Encoding.Default;
            }
            return Read(GetAbsolutePath(path), encode);
        }
        /// <summary>
        /// 读取文件（指定编码）
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="encode">编码方式</param>
        /// <returns></returns>
        public static string Read(string path, Encoding encode)
        {
            FileStream fs = null;
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                    break;
                }
                catch
                {
                    System.Threading.Thread.Sleep(50);
                }
            }
            if (fs == null) return "";
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(fs, encode);
                return sr.ReadToEnd();
            }
            catch (Exception)
            {
                // throw ex;
                return "";
            }
            finally
            {
                sr.Close();
                fs.Close();
            }
        }
        /// <summary>
        /// 返回文件行的数组
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static string[] ReadLines(string path)
        {
            return ReadLines(GetAbsolutePath(path), Encoding.Default);
        }
        /// <summary>
        /// 返回文件行的数组
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="encode">编码方式</param>
        /// <returns></returns>
        public static string[] ReadLines(string path, Encoding encode)
        {
            try
            {
                return System.IO.File.ReadAllLines(path, encode);
            }
            catch (Exception)
            {
                // throw ex;
                return null;
            }
        }
    }
}
