#region << 版 本 注 释 >>

/*--------------------------------------------------------------------
* 版权所有 (c) 2025 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：Mr.Wen's MacBook Pro
* 命名空间：Sln.Iot.CFX
* 唯一标识：B906AE83-E238-4BF5-A269-1A48D38158CC
*
* 创建者：WenJY
* 电子邮箱：
* 创建时间：2025-10-24 15:26:56
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/

#endregion << 版 本 注 释 >>

using System.Diagnostics;
using CFX;
using CFX.InformationSystem.UnitValidation;
using CFX.Production;
using CFX.ResourcePerformance;
using CFX.Structures;
using CFX.Transport;
using Sln.Iot.CFX.RequestReceived;

namespace Sln.Iot.CFX;

/// <summary>
/// CFX 帮助类
/// </summary>
public class CFXHelper
{
    private static readonly Lazy<CFXHelper> lazy = new Lazy<CFXHelper>(() => new CFXHelper());

    public static CFXHelper Instance
    {
        get
        {
            return lazy.Value;
        }
    }

    /// <summary>
    /// CFX通讯端点
    /// </summary>
    private readonly AmqpCFXEndpoint? _endpoint = new AmqpCFXEndpoint();

    public void Init(string cfxHandle, Uri uri, string address)
    {
        try
        {
            if (_endpoint == null)
            {
                throw new ArgumentNullException($"AmqpCFXEndpoint is null");
            }

            _endpoint.Open(cfxHandle, uri);

            _endpoint.AddPublishChannel(uri, address);

            _endpoint.OnRequestReceived -= Endpoint_OnRequestReceived;
            _endpoint.OnRequestReceived += Endpoint_OnRequestReceived;
        }
        catch (Exception e)
        {
            throw new InvalidOperationException($"CFX 接口初始化异常:{e.Message}");
        }
    }

    /// <summary>
    /// 请求接收处理
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    private CFXEnvelope Endpoint_OnRequestReceived(CFXEnvelope request)
    {
        CFXMessage response = null;

        if (request.MessageBody is AreYouThereRequest) //存在性检测请求
        {
            AreYouThereRequestReceived.Handle(request.MessageBody as AreYouThereRequest, out response);
        }
        else if (request.MessageBody is GetEndpointInformationRequest) //获取终端节点信息请求
        {
            GetEndpointInformationRequestReceived.Handle(request.MessageBody as GetEndpointInformationRequest, out response);
        }
        else if (request.MessageBody is WhoIsThereRequest) //设备存在性查询请求
        {
            WhoIsThereRequestReceived.Handle(request.MessageBody as WhoIsThereRequest, out response);
        }
        else if (request.MessageBody is GetActiveRecipeRequest) //获取当前激活配方请求
        {
            GetActiveRecipeRequestReceived.Handle(request.MessageBody as GetActiveRecipeRequest, out response);
        }
        else if (request.MessageBody is GetActiveFaultsRequest) //获取当前错误状态请求
        {
            GetActiveFaultsRequestReceived.Handle(request.MessageBody as GetActiveFaultsRequest, out response);
        }
        else if (request.MessageBody is HandleFaultRequest) //处理错误请求
        {
            HandleFaultRequestReceived.Handle(request.MessageBody as HandleFaultRequest, out response);
        }
        else if (request.MessageBody is ModifyStationParametersRequest) //设备修改参数请求
        {
            ModifyStationParametersRequestReceived.Handle(request.MessageBody as ModifyStationParametersRequest, out response);
        }
        else if (request.MessageBody is ValidateUnitsRequest) //生产单元验证请求
        {
            ValidateUnitsRequestReceived.Handle(request.MessageBody as ValidateUnitsRequest, out response);
        }
        else //不支持的请求类型
        {
            response = new NotSupportedResponse()
            {
                RequestResult = new RequestResult()
                {
                    Result = StatusResult.Failed,
                    ResultCode = 0,
                    Message = $"不支持的请求类型:{request.MessageBody.GetType().Name}"
                }
            };
        }

        CFXEnvelope env = new CFXEnvelope(response);
        return env;
    }

    /// <summary>
    /// 主动推送事件
    /// </summary>
    /// <param name="env"></param>
    public void PublishEvent(CFXEnvelope env)
    {
        try
        {
            if (_endpoint == null)
            {
                throw new ArgumentNullException($"AmqpCFXEndpoint is null");
            }

            _endpoint.Publish(env);
        }
        catch (Exception e)
        {
            throw new InvalidOperationException($"推送事件异常:{e.Message}");
        }
    }
}