using AyCode.Core.Logger;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System.Drawing;
using TIAM.Database.DataLayers.Admins;
using TIAM.Database.DataLayers.Auctions;
using TIAM.Entities.Auctions;
using TIAMWebApp.Shared.Application.Models;

namespace TIAMWebApp.Server.Controllers
{
    [Authorize]
    [ApiController]
    [EnableCors("_myAllowSpecificOrigins")]
    [Route("api/v1/[controller]")]
    public class FileAPIController : ControllerBase
    {
        private AdminDal _adminDal;
        private readonly IConfiguration _configuration;
        private readonly IWebHostEnvironment _webHostEnvironment;


        private readonly ILogger<FileAPIController> _logger;

        public FileAPIController(ILogger<FileAPIController> logger, IConfiguration configuration, IWebHostEnvironment webHostEnvironment, AdminDal adminDal)
        {
            _logger = logger;
            _configuration = configuration;
            _webHostEnvironment = webHostEnvironment;
            _adminDal = adminDal;
        }


        const long MaxFileSize = 4_000_000;
        readonly string[] imageExtensions = { ".JPG", ".JPEG", ".GIF", ".PNG" };


     
        [AllowAnonymous]
        [HttpPost]
        [Route(APIUrls.UploadImageRouteName)]
        public ActionResult UploadImage([FromForm] IFormFile file)
        {
            Console.WriteLine($"Upload file called: {file.FileName}");
            if (file == null || file.Length == 0)
                return BadRequest("File not selected");

            string folderPath = @"C:\CDN"; 
            string fileName = Path.GetFileNameWithoutExtension(file.FileName);
            string extension = Path.GetExtension(file.FileName).ToUpper();
            Console.WriteLine(extension);
            var isValidExtenstion = imageExtensions.Contains(extension);
            var isValidSize = file.Length <= MaxFileSize;
            if (!isValidExtenstion || !isValidSize) 
            { 
                return BadRequest("Invalid file");
            }

            string filePath = Path.Combine(folderPath, file.FileName);

            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            int count = 1;
            while (System.IO.File.Exists(filePath))
            {
                string tempFileName = string.Format("{0}({1})", fileName, count++);
                filePath = Path.Combine(folderPath, tempFileName + extension);
            }

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                file.CopyTo(stream);
            }

            return Ok(new { filePath });
        }


        [AllowAnonymous]
        [HttpGet]
        [Route(APIUrls.GetImagesRouteName)]
        public IActionResult GetAllMedia()
        {
            string folderPath = @"C:\CDN";

            if (!Directory.Exists(folderPath))
            {
                return NotFound("Directory not found");
            }

            var files = Directory.GetFiles(folderPath)
                                 .Select(Path.GetFileName)
                                 .ToList();

            return Ok(files);
        }

        [AllowAnonymous]
        //[HttpGet("Image/{name}")]
        [HttpGet("{APIUrls.GetImageRouteName}/{name}")]
        public IActionResult GetImage(string name)
        {
            string folderPath = @"C:\CDN"; 
            string filePath = Path.Combine(folderPath, name);

            if (!System.IO.File.Exists(filePath))
            {
                return NotFound("Image not found");
            }

            var image = System.IO.File.OpenRead(filePath);
            return File(image, "image/jpeg");
        }

    }
}