using System.Collections.Generic;
using System.Linq;
using Net.Eagle0.Eagle.Api;
using Net.Eagle0.Eagle.Common;

namespace eagle {

    public class ResolveInvitationCommandSelector : ResolveDiplomacyCommandSelector {
        private GeneratedTextListener messengerTextListener;
        private string cachedPrefixText = "";
        protected override IList<DiplomacyOffer> Offers =>
                _availableCommand?.ResolveInvitationCommand?.Invitations.ToList() ??
                new List<DiplomacyOffer>();

        protected override string PrefixedText(DiplomacyOffer offer) {
            SetupMessengerTextListener();
            return !string.IsNullOrEmpty(cachedPrefixText)
                           ? cachedPrefixText
                           : $"A messenger brings an invitation to join {Model.FactionName(OriginatingFactionId)}.\n";
        }

        private void ClearMessengerTextListener() {
            if (messengerTextListener != null) {
                ClientTextProvider.Provider.RemoveListener(messengerTextListener);
                messengerTextListener = null;
            }
        }

        private void SetupMessengerTextListener() {
            if (messengerTextListener != null) return;  // Already set up

            var messengerHero = Model.Heroes[MessengerHeroId];
            if (!string.IsNullOrEmpty(messengerHero.NameTextId)) {
                messengerTextListener = new GeneratedTextListener(
                        messengerHero.NameTextId,
                        "",
                        $" brings an invitation to join {Model.FactionName(OriginatingFactionId)}.\n",
                        0,
                        (index, text) => { cachedPrefixText = text; });

                ClientTextProvider.Provider.AddListener(messengerTextListener);
            }
        }
        protected override string TitleText => "Invited";

        public override SelectedCommand selectedCommand(DiplomacyOfferStatus resolution) =>
                new SelectedCommand {
                    ResolveInvitationCommand =
                            new ResolveInvitationSelectedCommand {
                                Resolution = resolution,
                                OriginatingFactionId = OriginatingFactionId
                            }
                };

        void OnDestroy() { ClearMessengerTextListener(); }
    }
}