using System;
using System.Collections.Generic;
using System.Linq;
using Net.Eagle0.Eagle.Views;

namespace eagle.Notifications {
    using PlayerId = Int32;

    public static class NewRoundNotificationGenerator {
        public static readonly NotificationGenerator Generator = GenerateNotification;

        private static IEnumerable<Notification> GenerateNotification(
                ActionResultView actionResultView,
                IGameModel currentModel) {
            if (currentModel.PlayerId is PlayerId pid) {
                var date = actionResultView.GameStateDiff.NewDate;
                var nextMonth = date.Month == 12 ? 1 : date.Month + 1;
                var nextYear = date.Month == 12 ? date.Year + 1 : date.Year;

                var myFaction = currentModel.MaybeDestroyedFaction(pid);
                foreach (var truce in myFaction.FactionRelationships.Where(
                                 t => t.RelationshipLevel == FactionRelationshipView.Types
                                                                     .RelationshipLevel.Truce &&
                                      t.ResetDate.Month == nextMonth &&
                                      t.ResetDate.Year == nextYear)) {
                    if (currentModel.ActiveFactions.ContainsKey(truce.TargetFactionId)) {
                        var expiringPartner =
                                currentModel.MaybeDestroyedFaction(truce.TargetFactionId);
                        var affectedProvinces =
                                currentModel.ProvincesForFaction(expiringPartner.Id);

                        var factionHead = currentModel.Heroes[expiringPartner.FactionHeadId];

                        yield return new Notification(
                            title: "Truce Expiring",
                            text:
                            $"Your treaty with {expiringPartner.Name} will expire in {DisplayNames.DateString(truce.ResetDate)}.",
                            provinceIds: affectedProvinces,
                            singleDisplayedHero: factionHead);
                    }
                }
            }
        }
    }
}