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

namespace eagle.Notifications {
    using HeroId = Int32;

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

        private static IEnumerable<Notification> GenerateNotification(
                ActionResultView actionResultView,
                IGameModel currentModel) {
            var playerId = currentModel.PlayerId;
            var province = currentModel.Provinces[actionResultView.Province.Value];
            HeroView leader = null;
            if (province.FullInfo != null && province.FullInfo.RulingHeroId is HeroId rulingHid) {
                leader = currentModel.Heroes[rulingHid];
            }
            string noteTitle = "Riot";
            string baseText = $"A riot seems to have occurred in {province.Name}.";
            var heroPlaceholders = new Dictionary<string, (string nameTextId, string fallback)>();

            HeroView killedHero = null;
            if (province.RulingFactionId.HasValue && province.RulingFactionId.Value == playerId) {
                baseText = $"A terrible riot has occurred in {province.Name}.";
                foreach (var removedHeroId in actionResultView.GameStateDiff.RemovedHeroIds) {
                    var hero = currentModel.Heroes[removedHeroId];
                    baseText += "\n";
                    baseText += $"{{KilledHero}} was killed in the riot!";
                    heroPlaceholders["KilledHero"] = (hero.NameTextId, "A hero");
                    killedHero = hero;
                    if (killedHero.Id == leader.Id) killedHero = null;
                }
            }

            var displayedHeroes =
                    new List<HeroView> { leader, killedHero }.Where(x => x != null).ToList();

            yield return new DynamicTextNotification(
                    title: noteTitle,
                    textTemplate: baseText,
                    heroPlaceholders: heroPlaceholders,
                    singleProvinceId: province.Id,
                    displayedHeroes: displayedHeroes);
        }
    }
}