using System.Collections.Generic;
using Aitex.Core.Utilities;
using MECF.Framework.UI.Client.ClientBase;
using Aitex.Core.RT.Event;
using System.Linq;
using AlarmInfoUi = Aitex.Core.UI.View.Common.AlarmItem;

namespace SicUI.Models.PMs
{
    public class PMAlarmViewModel : SicModuleUIViewModelBase, ISupportMultipleSystem
    {

        [IgnorePropertyChange]
        public List<AlarmInfoUi> AlarmEvents { get; set; }


        public PMAlarmViewModel()
        {
            Subscribe("System.LiveAlarmEvent");
        }

        protected override void InvokeBeforeUpdateProperty(Dictionary<string, object> data)
        {
            if (data.ContainsKey("System.LiveAlarmEvent"))
                UpdateAlarmEvent((List<EventItem>)data["System.LiveAlarmEvent"]);
        }

        public void UpdateAlarmEvent(List<EventItem> evItems)
        {
            var alarmEvents = new List<AlarmInfoUi>();
            foreach (EventItem item in evItems)
            {
                if (item.Source != SystemName)
                    continue;

                var it = new AlarmInfoUi()
                {
                    Level = item.Level,
                    OccuringTime = item.OccuringTime.ToString(),//item.OccuringTime.ToString("HH:mm:ss"),
                    Description = item.Description,
                    EventEnum = item.EventEnum,
                    EventId = item.Id,
                    Explaination = item.Explaination,
                    Solution = item.Solution,
                };
                
                alarmEvents.Add(it);
            }
            if (AlarmEvents == null || (alarmEvents.Count != AlarmEvents.Count))
            {
                AlarmEvents = alarmEvents;
            }
            else
            {
                bool isEqual = true;
                if (alarmEvents.Count == AlarmEvents.Count)
                {
                    for (int i = 0; i < alarmEvents.Count; i++)
                    {
                        if (!alarmEvents[i].IsEqualTo(AlarmEvents[i]))
                        {
                            isEqual = false;
                            break;
                        }
                    }
                }
                if (!isEqual)
                    AlarmEvents = alarmEvents;
            }

 			AlarmEvents = AlarmEvents.OrderBy(p=>p.OccuringTime).ToList();
            NotifyOfPropertyChange("AlarmEvents");
        }
    }
}
