#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 CFX;
using CFX.InformationSystem.UnitValidation;
using CFX.Production;
using CFX.ResourcePerformance;
using CFX.Structures;
using CFX.Transport;
using Microsoft.Identity.Client;
using Sln.Iot.CFX.Event;
using Sln.Iot.CFX.RequestReceived;
using Sln.Iot.Config;
using Sln.Iot.Serilog;
using System.Diagnostics;

namespace Sln.Iot.CFX;

/// <summary>
/// CFX 帮助类
/// </summary>
public abstract class CFXHelper
{
    SerilogHelper _log = SerilogHelper.Instance;

    private readonly AppConfig _appConfig = AppConfigSetting.Load();

    /// <summary>
    /// CFX通讯端点
    /// </summary>
    public AmqpCFXEndpoint? Endpoint = new AmqpCFXEndpoint();

    /// <summary>
    /// 初始化CFX接口
    /// </summary>
    /// <param name="cfxHandle"></param>
    /// <param name="selfURI"></param>
    /// <param name="upperURI"></param>
    /// <param name="address"></param>
    /// <returns></returns>
    /// <exception cref="InvalidOperationException"></exception>
    public void Init(string cfxHandle, Uri selfURI, Uri upperURI)
    {
        try
        {
            if (Endpoint == null)
            {
                throw new ArgumentNullException("CFX 端点无引用（null）");
            }

            Endpoint.Open(cfxHandle, selfURI);

            Endpoint.AddPublishChannel(upperURI, "event");

            Endpoint.OnRequestReceived -= Endpoint_OnRequestReceived;
            Endpoint.OnRequestReceived += Endpoint_OnRequestReceived;

            var connected = new EndpointConnectedEvent();
            PublishEvent(new CFXEnvelope(connected.Handle(cfxHandle, selfURI.ToString(), upperURI.ToString())));

        }
        catch (Exception ex)
        {
            SerilogHelper.Instance.Error("CFX接口启动异常", ex);
        }
    }

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

    /// <summary>
    /// 解耦请求处理
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    protected abstract CFXMessage HandleRequest(CFXEnvelope request);

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

            //Task.Run(() =>
            //{
            Endpoint.Publish(env);
            if (_appConfig.IsCFXLog)
                _log.Iot($"{Endpoint.CFXHandle}推送事件{env.MessageName}");
            //});
        }
        catch (Exception e)
        {
            throw new InvalidOperationException($"推送事件异常:{e.Message}");
        }
    }
}