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

namespace eagle.Notifications.ARNNotifications {
    using ProvinceId = Int32;

    public static class HeroReadyToJoinDetailsNotificationGenerator {
        public static readonly ARNNotificationGenerator Generator = GenerateNotifications;

        private static class Placeholders {
            public static readonly DynamicTextPlaceholderName ReadyHero = new(nameof(ReadyHero));
        }

        private static IEnumerable<Notification> GenerateNotifications(
                Net.Eagle0.Eagle.Common.Notification notification,
                IGameModel currentModel) {
            return GenerateNotifications(null, notification, currentModel);
        }

        public static IEnumerable<Notification> GenerateNotifications(
                ActionResultView actionResultView,
                Net.Eagle0.Eagle.Common.Notification notification,
                IGameModel currentModel) {
            var details = notification.Details.HeroReadyToJoinDetails;
            if (!TryFindHero(actionResultView, currentModel, details.HeroId, out var hero)) {
                Debug.LogWarning(
                        $"Skipping Ready to Join notification: hero {details.HeroId} is not present in the current model.");
                yield break;
            }
            if (!currentModel.Provinces.TryGetValue(details.ProvinceId, out var province)) {
                Debug.LogWarning(
                        $"Skipping Ready to Join notification: province {details.ProvinceId} is not present in the current model.");
                yield break;
            }

            var textTemplate = DynamicTextTemplate.Parsed(
                    $"{DynamicTextTemplate.Placeholder(Placeholders.ReadyHero)} is ready to join your faction in {province.Name}.\n\n");

            var heroPlaceholders = new List<DynamicPlaceholder> {
                DynamicPlaceholder.HeroName(Placeholders.ReadyHero, hero, "A hero")
            };

            yield return DynamicTextNotification.StreamingDynamicNotification(
                    title: "Ready to Join",
                    textTemplate: textTemplate,
                    placeholders: heroPlaceholders,
                    llmId: notification.LlmId,
                    provinceIds: new List<ProvinceId> { province.Id },
                    displayedHeroes: new List<HeroView> { hero });
        }

        private static bool TryFindHero(
                ActionResultView actionResultView,
                IGameModel currentModel,
                int heroId,
                out HeroView hero) {
            if (currentModel.Heroes.TryGetValue(heroId, out hero)) { return true; }

            hero = actionResultView?.GameStateDiff?.NewHeroes.FirstOrDefault(h => h.Id == heroId);
            return hero != null;
        }
    }
}
