using Hncore.Pass.Vpn.Service;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Linq;


namespace UEditor.Core.Handlers
{
    /// <summary>
    /// UploadHandler 的摘要说明
    /// </summary>
    public class AliUploadHandler : UploadHandler
    {       
        public AliUploadHandler(HttpContext context)
            : base(context)
        {
           
        }
   
       public  UploadService Uploader { get; set; }

        public override UEditorResult Process()
        {
            string uploadFileName = "";
            Stream stream = default(Stream);
            if (UploadConfig.Base64)
            {
                uploadFileName = UploadConfig.Base64Filename;
                var uploadFileBytes = Convert.FromBase64String(Request.Form[UploadConfig.UploadFieldName]);
                stream = new MemoryStream(uploadFileBytes);
            }
            else
            {
                var file = Request.Form.Files[UploadConfig.UploadFieldName];
                uploadFileName = file.FileName;
                if (!CheckFileType(uploadFileName))
                {
                    Result.State = UploadState.TypeNotAllow;
                    return WriteResult();
                }
                if (!CheckFileSize(file.Length))
                {
                    Result.State = UploadState.SizeLimitExceed;
                    return WriteResult();
                }
                try
                {
                    stream = file.OpenReadStream();
                }
                catch (Exception)
                {
                    Result.State = UploadState.NetworkError;
                    WriteResult();
                }
            }
            var fileKey = DateTime.Now.Ticks + new Random((int)DateTime.Now.Ticks).Next(0, 100000).ToString();
            Result.OriginFileName = uploadFileName;
            UEditorResult result;
            try
            {
                fileKey = $"{fileKey.ToString()}{Path.GetExtension(uploadFileName)}";
                var ret = Uploader.AliYunUpload(fileKey, Result.OriginFileName, stream);
                Result.Url = ret.Url;
                Result.State = UploadState.Success;
            }
            catch (Exception e)
            {
                Result.State = UploadState.FileAccessError;
                Result.ErrorMessage = e.Message;
            }
            finally
            {
                result = WriteResult();
            }

            return result;
        }

        private UEditorResult WriteResult()
        {
            return new UEditorResult
            {
                State = GetStateMessage(Result.State),
                Url = Result.Url,
                Title = Result.OriginFileName,
                Original = Result.OriginFileName,
                Error = Result.ErrorMessage
            };
        }

        private string GetStateMessage(UploadState state)
        {
            switch (state)
            {
                case UploadState.Success:
                    return "SUCCESS";
                case UploadState.FileAccessError:
                    return "文件访问出错，请检查写入权限";
                case UploadState.SizeLimitExceed:
                    return "文件大小超出服务器限制";
                case UploadState.TypeNotAllow:
                    return "不允许的文件格式";
                case UploadState.NetworkError:
                    return "网络错误";
            }
            return "未知错误";
        }

        private bool CheckFileType(string filename)
        {
            var fileExtension = Path.GetExtension(filename).ToLower();
            return UploadConfig.AllowExtensions.Select(x => x.ToLower()).Contains(fileExtension);
        }

        private bool CheckFileSize(long size)
        {
            return size < UploadConfig.SizeLimit;
        }
    }
}