using Serilog;
using Ayay.SerilogLogs;

namespace SHH.CameraSdk.DahuaFeatures;

/// <summary>
/// [大华功能组件] 预置点管理实现
/// <para>适配说明：使用 NETClient.PTZControl 接口，指令码为 10 (PTZ_POINT_CONTROL)</para>
/// </summary>
public class DahuaPresetProvider : IPresetFeature
{
    private ILogger _sdkLog = Log.ForContext("SourceContext", LogModules.DaHuaSdk);

    private readonly IDahuaContext _context;

    // 大华底层预置点控制命令常量
    private const uint PTZ_POINT_CONTROL = 10;

    public DahuaPresetProvider(IDahuaContext context)
    {
        _context = context;
    }

    /// <summary>跳转到预置点</summary>
    /// <param name="presetIndex">预置点编号 (1-255)</param>
    public async Task GotoPresetAsync(int presetIndex)
    {
        await ExecutePresetAction(presetIndex, 2, "调用");
    }

    /// <summary>设置/保存当前位置为预置点</summary>
    public async Task SetPresetAsync(int presetIndex)
    {
        await ExecutePresetAction(presetIndex, 0, "保存");
    }

    /// <summary>删除预置点</summary>
    public async Task RemovePresetAsync(int presetIndex)
    {
        await ExecutePresetAction(presetIndex, 1, "删除");
    }

    /// <summary>统一执行预置点动作</summary>
    /// <param name="index">编号</param>
    /// <param name="actionType">0:保存, 1:删除, 2:跳转</param>
    /// <param name="actionName">日志描述</param>
    private async Task ExecutePresetAction(int index, int actionType, string actionName)
    {
        IntPtr loginId = _context.GetUserId();
        if (loginId == IntPtr.Zero) return;

        await Task.Run(() =>
        {
            // Modified: [原因] 严格适配 NETClient.PTZControl 的 8 参数签名
            // lParam1: 0 (无意义)
            // lParam2: 预置点值 (nIndex)
            // lParam3: 动作类型 (0-保存, 1-删除, 2-跳转)
            bool result = NETClient.PTZControl(
                loginId,
                0,                  // nChannelID
                PTZ_POINT_CONTROL,  // dwPTZCommand = 10
                0,                  // lParam1
                index,              // lParam2: 预置点编号
                actionType,         // lParam3: 动作类型
                false,              // dwStop: 预置点操作不涉及停止位
                IntPtr.Zero         // param4
            );

            if (!result)
            {
                string error = NETClient.GetLastError();
                _sdkLog.Warning("[SDK] Dahua 预置点{Action}失败. Index: {Index}, Error: {Error}",
                            actionName, index, error);
            }
            else
            {
                _sdkLog.Debug("[SDK] Dahua 预置点{Action}成功. Index: {Index}", actionName, index);
            }
        });
    }
}