using System.Collections;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

namespace server.Controllers;

/// <summary>
/// 矩阵键控制器，用于管理矩阵键的启用、禁用和状态设置
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class MatrixKeyController : ControllerBase
{
    private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

    /// <summary>
    /// 启用矩阵键控制。
    /// </summary>
    /// <param name="address">设备的IP地址</param>
    /// <param name="port">设备的端口号</param>
    /// <returns>返回操作结果的状态码</returns>
    [HttpPost("EnabelMatrixKey")]
    [EnableCors("Users")]
    [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
    public async ValueTask<IResult> EnabelMatrixKey(string address, int port)
    {
        var matrixKeyCtrl = new Peripherals.MatrixKeyClient.MatrixKey(address, port);
        var ret = await matrixKeyCtrl.EnableControl();

        if (ret.IsSuccessful)
        {
            logger.Info($"Enable device {address}:{port.ToString()} matrix key finished: {ret.Value}.");
            return TypedResults.Ok(ret.Value);
        }
        else
        {
            logger.Error(ret.Error);
            return TypedResults.InternalServerError(ret.Error);
        }
    }

    /// <summary>
    /// 禁用矩阵键控制。
    /// </summary>
    /// <param name="address">设备的IP地址</param>
    /// <param name="port">设备的端口号</param>
    /// <returns>返回操作结果的状态码</returns>
    [HttpPost("DisableMatrixKey")]
    [EnableCors("Users")]
    [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
    public async ValueTask<IResult> DisableMatrixKey(string address, int port)
    {
        var matrixKeyCtrl = new Peripherals.MatrixKeyClient.MatrixKey(address, port);
        var ret = await matrixKeyCtrl.DisableControl();

        if (ret.IsSuccessful)
        {
            logger.Info($"Disable device {address}:{port.ToString()} matrix key finished: {ret.Value}.");
            return TypedResults.Ok(ret.Value);
        }
        else
        {
            logger.Error(ret.Error);
            return TypedResults.InternalServerError(ret.Error);
        }
    }

    /// <summary>
    /// 设置矩阵键的状态。
    /// </summary>
    /// <param name="address">设备的IP地址</param>
    /// <param name="port">设备的端口号</param>
    /// <param name="keyStates">矩阵键的状态数组，长度应为16</param>
    /// <returns>返回操作结果的状态码</returns>
    [HttpPost("SetMatrixKeyStatus")]
    [EnableCors("Users")]
    [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
    public async ValueTask<IResult> SetMatrixKeyStatus(string address, int port, [FromBody] bool[] keyStates)
    {
        if (keyStates.Length != 16)
            return TypedResults.BadRequest($"The length of key states should be 16 instead of {keyStates.Length}");

        var matrixKeyCtrl = new Peripherals.MatrixKeyClient.MatrixKey(address, port);
        var ret = await matrixKeyCtrl.ControlKey(new BitArray(keyStates));

        if (ret.IsSuccessful)
        {
            logger.Info($"Set device {address}:{port.ToString()} matrix key finished: {ret.Value}.");
            return TypedResults.Ok(ret.Value);
        }
        else
        {
            logger.Error(ret.Error);
            return TypedResults.InternalServerError(ret.Error);
        }
    }
}

