using Furion.VirtualFileServer;
using Microsoft.Extensions.Options;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using YBEE.EQM.Core;

namespace YBEE.EQM.Application;

/// <summary>
/// 资源文件管理服务
/// </summary>
[ApiDescriptionSettings(Name = "file")]
[Route("file")]
public class ResourceFileAppService(IResourceFileService resourceFileService, IOptions<EqmSiteOptions> options) : IDynamicApiController
{
    private readonly IResourceFileService _resourceFileService = resourceFileService;
    private readonly EqmSiteOptions _eqmSiteOptions = options.Value;

    //private readonly string[] thumbImageTypes = { ".png", ".jpg", "jpeg", ".gif", ".bmp" };

    /// <summary>
    /// 上传资源文件
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [RequestSizeLimit(long.MaxValue)]
    [RequestFormLimits(MultipartBodyLengthLimit = long.MaxValue)]
    public async Task<ResourceFileOutput> Upload([FromForm] UploadResourceFileInput input)
    {
        return await _resourceFileService.Upload(input);
    }

    /// <summary>
    /// 根据文件ID下载文件
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet, NonUnify]
    public async Task<IActionResult> Download([FromQuery][Required] long id)
    {
        var item = await _resourceFileService.GetById(id);
        var filePath = Path.Combine(_eqmSiteOptions.ResourceFileRoot, item.FilePath);
        return new FileStreamResult(new FileStream(filePath, FileMode.Open), "application/octet-stream")
        {
            FileDownloadName = item.FileName,
        };
    }

    /// <summary>
    /// 通过URL
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet, NonUnify, AllowAnonymous]
    public async Task<IActionResult> View([FromQuery][Required] long id)
    {
        var item = await _resourceFileService.GetById(id);
        var filePath = Path.Combine(_eqmSiteOptions.ResourceFileRoot, item.FilePath);
        if (File.Exists(filePath))
        {
            var fbs = await File.ReadAllBytesAsync(filePath);
            FS.TryGetContentType(filePath, out var contentType);
            var ret = new FileContentResult(fbs, contentType);
            //{
            //    FileDownloadName = item.FileName
            //};
            return ret;
        }
        throw Oops.Oh(ErrorCode.E1011);
    }
}
