private DayStackStats CreateBlankDayStackStats(DateTime occurrenceDate, string stackId, string projectId = null)
        {
            bool hasError = !String.IsNullOrEmpty(projectId);

            // store stats in 15 minute buckets
            var bucketCounts = new Dictionary <string, int>();

            for (int i = 0; i < 1440; i += 15)
            {
                if (hasError && i == GetTimeBucket(occurrenceDate))
                {
                    bucketCounts.Add(i.ToString("0000"), 1);
                }
            }

            var s = new DayStackStats {
                Id          = GetDayStackStatsId(stackId, occurrenceDate),
                ProjectId   = projectId,
                StackId     = stackId,
                Total       = hasError ? 1 : 0,
                MinuteStats = bucketCounts
            };

            return(s);
        }
        public StackStatsResult GetStackStatsByMinuteBlock(string stackId, TimeSpan utcOffset, DateTime?localStartDate = null, DateTime?localEndDate = null, DateTime?retentionStartDate = null)
        {
            // Round date range to blocks of 15 minutes since stats are per 15 minute block.
            var range = GetDateRange(localStartDate, localEndDate, utcOffset, TimeSpan.FromMinutes(15));

            if (range.Item1 == range.Item2)
            {
                return(new StackStatsResult());
            }

            DateTime utcStartDate = new DateTimeOffset(range.Item1.Ticks, utcOffset).UtcDateTime;
            DateTime utcEndDate   = new DateTimeOffset(range.Item2.Ticks, utcOffset).UtcDateTime;


            var results = _dayStackStats.GetRange(GetDayStackStatsId(stackId, utcStartDate), GetDayStackStatsId(stackId, utcEndDate));

            if (results.Count > 0)
            {
                DayStackStats firstWithOccurrence = results.OrderBy(r => r.Id).FirstOrDefault(r => r.MinuteStats.Any(ds => ds.Value > 0));
                if (firstWithOccurrence != null)
                {
                    DateTime firstErrorDate = firstWithOccurrence.GetDateFromMinuteStatKey(firstWithOccurrence.MinuteStats.OrderBy(ds => Int32.Parse(ds.Key)).First(ds => ds.Value > 0).Key);
                    if (utcStartDate < firstErrorDate)
                    {
                        utcStartDate = firstErrorDate;
                    }
                }
            }

            var      dayDocDates     = new List <DateTime>();
            DateTime currentDay      = utcStartDate;
            DateTime endOfDayEndDate = utcEndDate.ToEndOfDay();

            while (currentDay <= endOfDayEndDate)
            {
                dayDocDates.Add(currentDay);
                currentDay = currentDay.AddDays(1);
            }

            // add missing day documents
            foreach (DateTime dayDocDate in dayDocDates)
            {
                if (!results.Any(d => d.Id == GetDayStackStatsId(stackId, dayDocDate)))
                {
                    results.Add(CreateBlankDayStackStats(dayDocDate, stackId));
                }
            }

            // fill out missing minute blocks with blank stats
            foreach (DayStackStats r in results)
            {
                const int minuteBlocksInDay = 96;
                for (int i = 0; i <= minuteBlocksInDay - 1; i++)
                {
                    int minuteBlock = i * 15;
                    if (!r.MinuteStats.ContainsKey(minuteBlock.ToString("0000")))
                    {
                        r.MinuteStats.Add(minuteBlock.ToString("0000"), 0);
                    }
                }
            }

            if (retentionStartDate.HasValue)
            {
                retentionStartDate = retentionStartDate.Value.Floor(TimeSpan.FromMinutes(15));
            }

            var minuteBlocks = new List <KeyValuePair <DateTime, int> >();

            minuteBlocks = results.Aggregate(minuteBlocks, (current, result) => current.Concat(result.MinuteStats.ToDictionary(kvp => result.GetDateFromMinuteStatKey(kvp.Key), kvp => kvp.Value)).ToList())
                           .Where(kvp => kvp.Key >= utcStartDate && kvp.Key <= utcEndDate).OrderBy(kvp => kvp.Key).ToList();

            int totalLimitedByPlan = retentionStartDate != null && utcStartDate < retentionStartDate?minuteBlocks.Count(kvp => kvp.Key < retentionStartDate) : 0;

            if (totalLimitedByPlan > 0)
            {
                minuteBlocks = minuteBlocks.Where(kvp => kvp.Key >= retentionStartDate).ToList();
            }

            // group data points by a timespan to limit the number of returned data points
            TimeSpan groupTimeSpan = TimeSpan.FromMinutes(15);

            if (minuteBlocks.Count > 50)
            {
                DateTime first = minuteBlocks.Min(m => m.Key);
                DateTime last  = minuteBlocks.Max(m => m.Key);
                TimeSpan span  = last - first;
                groupTimeSpan = TimeSpan.FromMinutes(((int)Math.Round(span.TotalMinutes / 50 / 15.0)) * 15);
            }

            var stats = new StackStatsResult {
                TotalLimitedByPlan = totalLimitedByPlan,
                StartDate          = utcStartDate,
                EndDate            = utcEndDate,
                Total = minuteBlocks.Sum(kvp => kvp.Value),
                Stats = minuteBlocks.GroupBy(s => s.Key.Floor(groupTimeSpan)).Select(kvp => new DateStackStatsResult {
                    Date  = kvp.Key,
                    Total = kvp.Sum(b => b.Value)
                }).ToList()
            };

            stats.ApplyTimeOffset(utcOffset);

            return(stats);
        }