using IntegrateTinyMCE.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Text.Json;

namespace IntegrateTinyMCE.Controllers;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly IWebHostEnvironment _hostingEnvironment;

    public HomeController(ILogger<HomeController> logger, IWebHostEnvironment hostingEnvironment)
    {
        _logger = logger;
        _hostingEnvironment = hostingEnvironment;
    }

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

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

    [HttpPost]
    public IActionResult Privacy(string? content)
    {
        if (content is not null)
            ViewBag.Content = content;

        return View();
    }

    public async Task<string> UploadEditorImg()
    {
        IFormFile img = Request.Form.Files[0];
        string path = Path.Combine(_hostingEnvironment.WebRootPath, "img/");

        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);

        await using FileStream stream = new FileStream(path + img.FileName, FileMode.Create);
        await img.CopyToAsync(stream);

        return JsonSerializer.Serialize(new { location = Path.Combine("/img/", img.FileName) });
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}