using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NoticeBoard.Data;

namespace NoticeBoard.Controllers;

public class DisplayController : Controller
{
    private readonly AppDbContext _db;

    public DisplayController(AppDbContext db)
    {
        _db = db;
    }

    public async Task<IActionResult> Show(string slug)
    {
        var device = await _db.Devices
            .Include(d => d.DeviceSlides.Where(ds => ds.Enabled).OrderBy(ds => ds.DisplayOrder))
                .ThenInclude(ds => ds.Slide)
            .FirstOrDefaultAsync(d => d.Slug == slug.ToLower());

        if (device == null)
        {
            var devices = await _db.Devices.OrderBy(d => d.Name).ToListAsync();
            return View("NotFound", devices);
        }

        return View(device);
    }

    [HttpGet]
    [Route("api/playlist/{slug}")]
    public async Task<IActionResult> GetPlaylist(string slug)
    {
        var device = await _db.Devices
            .Include(d => d.DeviceSlides.Where(ds => ds.Enabled).OrderBy(ds => ds.DisplayOrder))
                .ThenInclude(ds => ds.Slide)
            .FirstOrDefaultAsync(d => d.Slug == slug.ToLower());

        if (device == null) return NotFound();

        var playlist = device.DeviceSlides.Select(ds => new
        {
            id = ds.Slide.Id,
            name = ds.Slide.Name,
            type = ds.Slide.SlideType.ToString().ToLower(),
            content = ds.Slide.Content,
            embedUrl = ds.Slide.EmbedUrl,
            icsSource = ds.Slide.IcsSource,
            backgroundColor = ds.Slide.BackgroundColor,
            backgroundImage = ds.Slide.BackgroundImage,
            backgroundSize = ds.Slide.BackgroundSize,
            customCss = ds.Slide.CustomCss,
            duration = ds.DurationSeconds,
            updatedAt = ds.Slide.UpdatedAt
        });

        return Json(new
        {
            device = new
            {
                name = device.Name,
                slug = device.Slug,
                width = device.ResolutionWidth,
                height = device.ResolutionHeight,
                transition = device.Transition
            },
            slides = playlist
        });
    }
}
