using System;
using Aitex.Core.RT.Log;
using Aitex.Core.Util;

namespace Aitex.Core.RT.IOCore.Interlock.DataProvider;

public abstract class DataPollProviderBase<T> : IInterlockLimitDataProvider
{
    #region Variables

    private readonly R_TRIG _rTrigPollFailed = new();

    #endregion
    
    #region Constructors

    /// <summary>
    /// 实例化数据拉取器
    /// </summary>
    /// <param name="dataPath"></param>
    protected DataPollProviderBase(string dataPath)
    {
        DataPath = dataPath;
    }

    #endregion

    #region Properties

    /// <summary>
    /// <inheritdoc cref="DataPollProviderBase{T}.Name"/>
    /// </summary>
    public string Name => DataPath;

    /// <summary>
    /// <inheritdoc cref="DataPollProviderBase{T}.Description"/>
    /// </summary>
    public string Description => DataPath;
    
    
    /// <summary>
    /// 返回当前数据拉取器需要拉取的数据路径。
    /// <remarks>
    /// 注意路径中不要包含Module名称。
    /// </remarks>
    /// </summary>
    protected string DataPath { get; }

    #endregion

    #region Methods

    /// <summary>
    /// 需由派生类实现的获取数据的方法。
    /// </summary>
    /// <returns></returns>
    protected abstract object HandleGetValue();

    /// <summary>
    /// 获取数据。
    /// </summary>
    /// <returns></returns>
    public object GetValue()
    {
        try
        {
            var value = HandleGetValue();
            _rTrigPollFailed.CLK = false;
            return value;
        }
        catch (Exception ex)
        {
            _rTrigPollFailed.CLK = true;
            if (_rTrigPollFailed.Q)
            {
                LOG.Error($"DataPollProvider poll data {DataPath} failed, {ex.Message}");
            }

            return null;
        }  
    }

    public override string ToString()
    {
        return Name;
    }

    #endregion

}