<commit_before>﻿using BatteryCommander.Web.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Services
{
    public class CalendarService
    {
        private const string DateFormat = "yyyyMMddTHHmmssZ";

        private static IEnumerable<int> YearsToGenerate => Enumerable.Range(DateTime.Today.Year, 3);

        //[AllowAnonymous, Route("~/Calendar")]
        public static async Task<byte[]> Generate(Database db, int unitId, String apikey)
        {
            var unit =
                await db
                .Units
                .Where(_ => _.Id == unitId)
                .SingleOrDefaultAsync();

            // TODO Verify API key

            // Get the raw data

            var soldiers = await SoldierSearchService.Filter(db, new SoldierSearchService.Query { Unit = unitId });

            var evaluations = 
                await db
                .Evaluations
                .Where(evaluation => !evaluation.IsCompleted)
                .ToListAsync();

            // Build model

            var sb = new StringBuilder()
                .AppendLine("BEGIN:VCALENDAR")
                .AppendLine("PRODID:-//Red-Leg-Dev//Battery Commander//EN")
                .AppendLine("VERSION:2.0")
                .AppendLine("METHOD:PUBLISH");

            foreach (var entry in Generate_For_Birthdays(soldiers))
            {
                sb = sb.Append(To_Event(entry));
            }

            foreach (var entry in Generate_For_Evaluations(evaluations))
            {
                sb = sb.Append(To_Event(entry));
            }

            sb = sb.AppendLine("END:VCALENDAR");

            // Return iCal Feed

            // return File(bytes, "text/calendar");

            return Encoding.UTF8.GetBytes(sb.ToString());
        }

        private static IEnumerable<Entry> Generate_For_Evaluations(IEnumerable<Evaluation> evaluations)
        {
            foreach (var evaluation in evaluations)
            {
                yield return new Entry
                {
                    Description = $"{evaluation.Ratee.Rank} {evaluation.Ratee.LastName} Eval Thru-Date",
                    Date = evaluation.ThruDate
                };
            }
        }

        private static IEnumerable<Entry> Generate_For_Birthdays(IEnumerable<Soldier> soldiers)
        {
            foreach (var soldier in soldiers)
            {
                if (soldier.HasDoB)
                {
                    foreach (var year in YearsToGenerate)
                    {
                        yield return new Entry
                        {
                            Description = $"{soldier.Rank} {soldier.LastName} Birthday",
                            Date = new DateTime(year, soldier.DateOfBirth.Month, soldier.DateOfBirth.Day)
                        };
                    }<commit_msg>Also generate for ETSdates<commit_after>﻿using BatteryCommander.Web.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Services
{
    public class CalendarService
    {
        private const string DateFormat = "yyyyMMddTHHmmssZ";

        private static IEnumerable<int> YearsToGenerate => Enumerable.Range(DateTime.Today.Year, 3);

        //[AllowAnonymous, Route("~/Calendar")]
        public static async Task<byte[]> Generate(Database db, int unitId, String apikey)
        {
            var unit =
                await db
                .Units
                .Where(_ => _.Id == unitId)
                .SingleOrDefaultAsync();

            // TODO Verify API key

            // Get the raw data

            var soldiers = await SoldierSearchService.Filter(db, new SoldierSearchService.Query { Unit = unitId });

            var evaluations =
                await db
                .Evaluations
                .Where(evaluation => !evaluation.IsCompleted)
                .ToListAsync();

            // Build model

            var sb = new StringBuilder()
                .AppendLine("BEGIN:VCALENDAR")
                .AppendLine("PRODID:-//Red-Leg-Dev//Battery Commander//EN")
                .AppendLine("VERSION:2.0")
                .AppendLine("METHOD:PUBLISH");

            new[]
            {
                Generate_For_Birthdays(soldiers),
                Generate_For_ETS_Dates(soldiers),
                Generate_For_Evaluations(evaluations)
            }
            .SelectMany(_ => _)
            .Select(entry => To_Event(entry))
            .ToList()
            .ForEach(entry => sb.Append(entry));

            sb = sb.AppendLine("END:VCALENDAR");

            // Return iCal Feed

            // return File(bytes, "text/calendar");

            return Encoding.UTF8.GetBytes(sb.ToString());
        }

        private static IEnumerable<Entry> Generate_For_Evaluations(IEnumerable<Evaluation> evaluations)
        {
            foreach (var evaluation in evaluations)
            {
                yield return new Entry
                {
                    Description = $"{evaluation.Ratee.Rank} {evaluation.Ratee.LastName} Eval Thru-Date",
                    Date = evaluation.ThruDate
                };
            }
        }

        private static IEnumerable<Entry> Generate_For_ETS_Dates(IEnumerable<Soldier> soldiers)
        {
            foreach (var soldier in soldiers)
            {
                if (soldier.ETSDate.HasValue)
                {
                    yield return new Entry
                    {
                        Description = $"{soldier.Rank} {soldier.LastName} ETS",
                        Date = soldier.ETSDate.Value
                    };
                }
            }
        }

        private static IEnumerable<Entry> Generate_For_Birthdays(IEnumerable<Soldier> soldiers)
        {
            foreach (var soldier in soldiers)
            {
                if (soldier.HasDoB)
                {
                    foreach (var year in YearsToGenerate)
                    {
                        yield return new Entry
                        {
                            Description = $"{soldier.Rank} {soldier.LastName} Birthday",
                            Date = new DateTime(year, soldier.DateOfBirth.Month, soldier.DateOfBirth.Day)
                        };
                    }
{'fraction_non_alphanumeric': 0.08883756735950732, 'fraction_numerical': 0.0012317167051578138, 'mean_word_length': 1.4457831325301205, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 26, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3947908', 'n_tokens_mistral': 1690, 'n_tokens_neox': 1553, 'n_words': 343}