using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using server.Services;

namespace server.Controllers;

[ApiController]
[Route("api/[controller]")]
[EnableCors("Users")]
public class HdmiVideoStreamController : ControllerBase
{
    private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

    private readonly HttpHdmiVideoStreamService _videoStreamService;
    private readonly Database.UserManager _userManager;

    public HdmiVideoStreamController(HttpHdmiVideoStreamService videoStreamService, Database.UserManager userManager)
    {
        _videoStreamService = videoStreamService;
        _userManager = userManager;
    }

    // 管理员获取所有板子的 endpoints
    [HttpGet("AllEndpoints")]
    [Authorize("Admin")]
    public ActionResult<List<HdmiVideoStreamEndpoint>> GetAllEndpoints()
    {
        var endpoints = _videoStreamService.GetAllVideoEndpoints();
        if (endpoints == null)
            return NotFound("No boards found.");
        return Ok(endpoints);
    }

    // 用户获取自己板子的 endpoint
    [HttpGet("MyEndpoint")]
    [Authorize]
    public ActionResult<HdmiVideoStreamEndpoint> GetMyEndpoint()
    {
        var userName = User.FindFirstValue(ClaimTypes.Name);
        if (string.IsNullOrEmpty(userName))
            return Unauthorized("User name not found in claims.");

        var userRet = _userManager.GetUserByName(userName);
        if (!userRet.IsSuccessful || !userRet.Value.HasValue)
            return NotFound("User not found.");

        var user = userRet.Value.Value;
        var boardId = user.BoardID;
        if (boardId == Guid.Empty)
            return NotFound("No board bound to this user.");

        var boardRet = _userManager.GetBoardByID(boardId);
        if (!boardRet.IsSuccessful || !boardRet.Value.HasValue)
            return NotFound("Board not found.");

        var endpoint = _videoStreamService.GetVideoEndpoint(boardId.ToString());
        return Ok(endpoint);
    }

    // 禁用指定板子的 HDMI 传输
    [HttpPost("DisableHdmiTransmission")]
    [Authorize]
    public async Task<IActionResult> DisableHdmiTransmission()
    {
        var userName = User.FindFirstValue(ClaimTypes.Name);
        if (string.IsNullOrEmpty(userName))
            return Unauthorized("User name not found in claims.");

        var userRet = _userManager.GetUserByName(userName);
        if (!userRet.IsSuccessful || !userRet.Value.HasValue)
            return NotFound("User not found.");

        var user = userRet.Value.Value;
        var boardId = user.BoardID;
        if (boardId == Guid.Empty)
            return NotFound("No board bound to this user.");

        try
        {
            await _videoStreamService.DisableHdmiTransmissionAsync(boardId.ToString());
            return Ok($"HDMI transmission for board {boardId} disabled.");
        }
        catch (Exception ex)
        {
            logger.Error(ex, $"Failed to disable HDMI transmission for board {boardId}");
            return StatusCode(500, $"Error disabling HDMI transmission: {ex.Message}");
        }
    }
}
