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 class Placeholders {
            public static readonly DynamicTextPlaceholderName KilledHero = new(nameof(KilledHero));
        }

        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";
            var textTemplate = DynamicTextTemplate.Parsed(
                    $"A riot seems to have occurred in {province.Name}.");
            var heroPlaceholders = new List<DynamicPlaceholder>();

            HeroView killedHero = null;
            if (province.RulingFactionId.HasValue && province.RulingFactionId.Value == playerId) {
                if (leader == null) {
                    throw new InvalidOperationException(
                            $"Player-owned riot province {province.Id} is missing a ruling hero.");
                }
                textTemplate = DynamicTextTemplate.Parsed(
                        $"A terrible riot has occurred in {province.Name}.");
                foreach (var removedHeroId in actionResultView.GameStateDiff.RemovedHeroIds) {
                    var hero = currentModel.Heroes[removedHeroId];
                    var killedHeroPlaceholder =
                            Placeholders.KilledHero.WithNumericSuffix(heroPlaceholders.Count + 1);
                    textTemplate = textTemplate.WithParsedSuffix("\n");
                    textTemplate = textTemplate.WithParsedSuffix(
                            $"{DynamicTextTemplate.Placeholder(killedHeroPlaceholder)} was killed in the riot!");
                    heroPlaceholders.Add(
                            DynamicPlaceholder.HeroName(killedHeroPlaceholder, hero, "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: textTemplate,
                    placeholders: heroPlaceholders,
                    singleProvinceId: province.Id,
                    displayedHeroes: displayedHeroes);
        }
    }
}
