using System;
using System.Runtime.Serialization;
using Aitex.Core.RT.Event;

namespace MECF.Framework.Common.Event
{
	[Serializable]
	[DataContract]
	public class AlarmEventItem : EventItem
	{
        #region Variables

        private IAlarmHandler _alarmHandler;

		private bool _ignoreAlarm;

        #endregion

        #region Constructors

        public AlarmEventItem(string source, string name, string description, Func<bool> resetChecker, IAlarmHandler handler)
			: base(source, name, description, EventLevel.Alarm, EventType.EventUI_Notify)
		{
			ResetChecker = resetChecker;
			IsAcknowledged = true;
			_alarmHandler = handler;
		}

        #endregion

        #region Properties

        /// <summary>
        /// 设置或返回报警复位检查器。
        /// </summary>
        public Func<bool> ResetChecker { get; set; }

        #endregion

        #region Methods

        /// <summary>
        /// 设置当前报警是否可被忽略。
        /// </summary>
        /// <param name="ignore">
        /// <value>True：忽略当前报警</value>
        /// </param>
        public void SetIgnoreError(bool ignore)
		{
			if (_ignoreAlarm == ignore)
				return;

			_ignoreAlarm = ignore;
			if (ignore)
			{
				EV.PostWarningLog(Source, Source + " " + EventEnum + " error will be ignored");
                if (!IsTriggered)
                    return;

                IsAcknowledged = true;
                _alarmHandler?.AlarmStateChanged(this);
            }
			else
			{
				Reset();
			}
		}

        /// <summary>
        /// 复位报警。
        /// </summary>
        /// <remarks>
        /// 报警复位后，其应答状态<see cref="EventItem.IsAcknowledged"/>将被设置为True。
        /// </remarks>
        public void Reset()
        {
            if (_ignoreAlarm || !IsTriggered || (ResetChecker != null && !ResetChecker())) 
                return;

            EV.PostInfoLog(Source, Source + " " + EventEnum + " is cleared");
            IsAcknowledged = true;
            _alarmHandler?.AlarmStateChanged(this);
        }

        /// <summary>
        /// 重置报警应答状态和报警时间。
        /// </summary>
        public void Set()
		{
			Set(null);
		}

		/// <summary>
		/// 设置报警内容，并重置报警应答状态和报警时间。
		/// </summary>
		/// <param name="error">报警内容描述。</param>
		public void Set(string error)
        {
            if (_ignoreAlarm || IsTriggered) 
                return;

            if (!string.IsNullOrEmpty(error))
            {
                Description = error;
            }

            IsAcknowledged = false;
            OccuringTime = DateTime.Now;
            _alarmHandler?.AlarmStateChanged(this);
        }
        
        #endregion
    }
}
