
using FMSAdmin.Data;

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using FMSAdmin.Helpers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authorization;
using System;
using System.IO;

namespace FMSAdmin.Controllers {
    [ApiController]
    [ApiVersion("1")]
    [Route("api/[controller]")]
    public class ControlController : Controller {
        private readonly ILogger<ControlController> _logger;
        private readonly FMSContext _context;
        private readonly StorageHelper _storage;

        public ControlController(
            ILogger<ControlController> logger,
            FMSContext context,
            StorageHelper storage
            ) {
            _logger = logger;
            _context = context;
            _storage = storage;
        }

        [HttpPost]
        [Route("[action]")]
        public IActionResult Upload(IFormFile file) {
            var uploadFile = _storage.SaveTemp(file);

            return Ok(uploadFile);
        }

        [HttpPost]
        [Route("[action]")]
        public IActionResult UploadImage(IFormFile file) {
            var uploadFile = _storage.SaveTempImage(file);

            return Ok(uploadFile);
        }

        /// <summary>
        /// 웹에디터 업로드
        /// </summary>
        [HttpPost]
        [Route("[action]")]
        public IActionResult FroalaImageUpload(IFormFile file) {
            var today = DateTime.Now.ToString("yyyy-MM-dd");
            _storage.CreateDirectory($"/editor/{today}");

            // 파일명 중복처리
            var filename = file.FileName;
            var ext = Path.GetExtension(filename);
            var name = Path.GetFileNameWithoutExtension(filename);
            var filePath = $"/editor/{today}/{filename}";
            var count = 0;
            while (_storage.FileExists(filePath)) {
                filename = name + ("(" + (count + 1) + ")") + (ext.Length > 0 ? ext : "");
                filePath = $"/editor/{today}/{filename}";
                _logger.LogInformation("filePath:" + filePath);
                count++;
            }

            var uploadFile = _storage.SaveImage(filePath, file);

            return Ok(new {
                link = uploadFile.Url
            });
        }

    }
}