using Csla;
using SyncfusionSchedulerDeleteBug.Business.Interfaces;
using SyncfusionSchedulerDeleteBug.DataAccess.Events;
using System;
using System.Collections.Generic;
using System.Linq;

namespace SyncfusionSchedulerDeleteBug.Business.Events
{
    [Serializable]
    public class CalendarEventsList : BusinessListBase<CalendarEventsList, CalendarEventInfo>, IHoldOffsetDates
    {
        #region business methods

        public bool OffsetApplied { get; set; }

        public void ApplyUserOffset(TimeSpan offset)
        {
            if (OffsetApplied)
                return;

            foreach (var e in this)
            {
                e.ApplyUserOffset(offset);
            }

            OffsetApplied = true;
        }

        public List<CalendarEventInfo> GetEventsForRange(DateTime from, DateTime to)
        {
            return this.Where(x => (x.StartTime >= from && x.StartTime <= to) || 
                                   (x.LastOccurenceDate >= from && x.LastOccurenceDate <= to ) ||
                                   (x.StartTime <= from && x.LastOccurenceDate >= to)).ToList();
        }

        #endregion

        #region data access       

        [Fetch]
        private void Fetch(DateRangeCriteria dates, [Inject] IEventsDal dal)
        {
            var rlce = RaiseListChangedEvents;
            RaiseListChangedEvents = false;

            var result = dal.GetCalendarEvents(dates.FromDate, dates.ToDate);
            foreach (var e in result)
            {
                Add(DataPortal.FetchChild<CalendarEventInfo>(e));
            }

            rlce = RaiseListChangedEvents;
        }

        #endregion

    }
}
