using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SecureSharing.Business.Dtos;
using SecureSharing.Business.Interfaces;
using SecureSharing.Data.Data;
using SecureSharing.Infrastructure;
using SecureSharing.Models;

namespace SecureSharing.Controllers;

[Authorize]
public sealed class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly IMessageService _messageService;
    private readonly IModelFactory _modelFactory;
    private readonly IWebHostEnvironment _webHostEnvironment;
    private const string DefaultPath = "files";
    
    public HomeController(ILogger<HomeController> logger, IMessageService messageService, IModelFactory modelFactory, IWebHostEnvironment webHostEnvironment)
    {
        _logger = logger;
        _messageService = messageService;
        _modelFactory = modelFactory;
        _webHostEnvironment = webHostEnvironment;
    }

    public IActionResult Index()
    {
        return View();
    }


    [HttpPost]
    public async Task<IActionResult> CreateMessage(MessageModel model)
    {
        if (string.IsNullOrWhiteSpace(model.Text) && model.Files.Count == 0)
        {
            return Redirect("/");
        }
        
        var message = new MessageDto { Text = model.Text };
        
        // var basePath = Path.Combine(_webHostEnvironment.WebRootPath.Split('/')[0], DefaultPath, message.Code.ToString());
        var basePath = $"C:\\Users\\radivoje.milutinovic\\Downloads\\fajlovitmp\\{message.Code}";
        
        Directory.CreateDirectory(basePath);

        foreach (var formFile in model.Files)
        {
            if (formFile.Length <= 0) continue;
            // Console.WriteLine(JsonSerializer.Serialize(formFile));
            var filePath = Path.Combine(basePath, formFile.FileName);
            await using var stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite);
            await formFile.CopyToAsync(stream);
            message.FileNames.Add(new FileModel { Name = formFile.FileName });
        }
        
        var code = await _messageService.Create(message, model.ChosenPeriod);
        return RedirectToAction("Link", "Home", new { code = code, share = true });
    }

    [HttpGet]
    public async Task<IActionResult> Link(Guid code, bool? share)
    {
        var model = await _modelFactory.PrepareLinkVM(code, share);
        return View(model);
    }


    public IActionResult Privacy()
    {
        return View();
    }
}