using System.Net;
using DotNext;

namespace Peripherals.PowerClient;

class PowerAddr
{
    public const UInt32 Base = 0x10_00_00_00;
    public const UInt32 PowerCtrl = Base + 7;
}

/// <summary>
/// [TODO:description]
/// </summary>
public class Power
{
    private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

    readonly int timeout;

    readonly int port;
    readonly string address;
    private IPEndPoint ep;

    /// <summary>
    /// [TODO:description]
    /// </summary>
    /// <param name="address">[TODO:parameter]</param>
    /// <param name="port">[TODO:parameter]</param>
    /// <param name="timeout">[TODO:parameter]</param>
    /// <returns>[TODO:return]</returns>
    public Power(string address, int port, int timeout = 1000)
    {
        this.address = address;
        this.port = port;
        this.ep = new IPEndPoint(IPAddress.Parse(address), port);
        this.timeout = timeout;
    }

    /// <summary>
    /// [TODO:description]
    /// </summary>
    /// <param name="enable">[TODO:parameter]</param>
    /// <returns>[TODO:return]</returns>
    public async ValueTask<Result<bool>> SetPowerOnOff(bool enable)
    {
        if (MsgBus.IsRunning)
            MsgBus.UDPServer.ClearUDPData(this.address, 1);
        else return new(new Exception("Message Bus not work!"));

        var ret = await UDPClientPool.WriteAddr(this.ep, 1, PowerAddr.PowerCtrl, Convert.ToUInt32(enable), this.timeout);
        if (!ret.IsSuccessful) return new(ret.Error);
        return ret.Value;
    }
}

