using System;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.UI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;

namespace YGNT.File.Core.Domain
{
    public class FileManager : IFileManager
    {
        private readonly IRepository<File, Guid> _fileRepository;
        private readonly IWebHostEnvironment _webHostEnvironment;

        public FileManager(IRepository<File, Guid> fileRepository, IWebHostEnvironment webHostEnvironment)
        {
            _fileRepository = fileRepository;
            _webHostEnvironment = webHostEnvironment;
        }

        /// <summary>
        /// 检测文件md5 是否已经存在
        /// </summary>
        /// <param name="md5"></param>
        /// <returns></returns>
        public async Task<Guid?> VerifyMd5Async(string md5)
        {
            var file = await _fileRepository.GetAll()
                .Where(x => x.Md5 == md5)
                .FirstOrDefaultAsync();
            return file?.Id;
        }

        /// <summary>
        /// 录入文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task<File> CreateAsync(string filePath)
        {
            var fileInfo = new FileInfo(filePath);
            if (!fileInfo.Exists)
                throw new UserFriendlyException($"文件路径:{filePath}不存在!");
            var file = new File()
            {
                FileName = fileInfo.Name,
                Suffix = fileInfo.Extension,
                Size = fileInfo.Length,
                Path = Path.GetRelativePath(_webHostEnvironment.WebRootPath, filePath),
                //PhysicsPath = filePath
            };
            await using (var fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read))
            {
                //获取md5值
                System.Security.Cryptography.MD5 md5Crypto = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5Crypto.ComputeHash(fileStream);
                StringBuilder sb = new StringBuilder();
                foreach (var t in retVal)
                {
                    sb.Append(t.ToString("x2"));
                }
                file.Md5 = sb.ToString();
            }
            await _fileRepository.InsertAndGetIdAsync(file);
            return file;
        }

        /// <summary>
        /// 录入文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public File Create(string filePath, string fileName = null)
        {
            var fileInfo = new FileInfo(filePath);
            if (!fileInfo.Exists)
                throw new UserFriendlyException($"文件路径:{filePath}不存在!");
            var file = new File()
            {
                FileName = fileName.IsNullOrEmpty() ? fileInfo.Name : fileName,
                Suffix = fileInfo.Extension,
                Size = fileInfo.Length,
                Path = Path.GetRelativePath(_webHostEnvironment.WebRootPath, filePath),
                //PhysicsPath = filePath
            };
            using (var fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read))
            {
                //获取md5值
                System.Security.Cryptography.MD5 md5Crypto = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5Crypto.ComputeHash(fileStream);
                StringBuilder sb = new StringBuilder();
                foreach (var t in retVal)
                {
                    sb.Append(t.ToString("x2"));
                }
                file.Md5 = sb.ToString();
            }
            _fileRepository.InsertAndGetId(file);
            return file;
        }
    }
}