using System;
using System.Collections.Generic;
using System.Linq;
using Net.Eagle0.Eagle.Api;
using Net.Eagle0.Eagle.Api.Command.Util;
using TMPro;
using UnityEngine.UI;

namespace eagle {
    using HeroId = Int32;
    using ProvinceId = Int32;

    public class RecruitHeroesCommandSelector : CommandSelector {
        public HeroDetailsController heroDetails;
        public Button nextHeroButton;
        public TMP_Text statusText;
        public GeneratedTextUpdater backstoryText;

        private int _selectedHeroIndex;

        private RecruitHeroesAvailableCommand RecruitHeroesCommand =>
                _availableCommand.RecruitHeroesCommand;
        private ProvinceId ActingProvinceId => RecruitHeroesCommand.ActingProvinceId;
        private ExpandedUnaffiliatedHero SelectedHero =>
                RecruitHeroesCommand.AvailableHeroes.ToList()[_selectedHeroIndex];
        private int HeroCount => RecruitHeroesCommand.AvailableHeroes.Count;

        public override AvailableCommand.SealedValueOneofCase CommandType =>
                AvailableCommand.SealedValueOneofCase.RecruitHeroesCommand;
        public override string HeaderString => "Recruit Heroes";
        public override string CommitButtonString => "Commit Recruit";

        public override bool HeroIsTargetable(HeroId heroId) =>
                RecruitHeroesCommand.AvailableHeroes.Any(euh => euh.Hero.Id == heroId);
        public override List<HeroId> TargetedHeroIds => new List<HeroId> { SelectedHero.Hero.Id };

        void DisplayHero() {
            heroDetails.SetHero(SelectedHero.Hero, _model);
            statusText.text = DisplayNames.UnaffiliatedHeroStatus(SelectedHero.Type);
            backstoryText.TextId = SelectedHero.Hero.BackstoryTextId;
            nextHeroButton.gameObject.SetActive(HeroCount > 1);
        }

        protected override void SetUpUI() {
            if (_selectedHeroIndex >= HeroCount) { _selectedHeroIndex = 0; }
            DisplayHero();
            nextHeroButton.gameObject.SetActive(HeroCount > 1);
        }

        public override SelectedCommand Command {
            get {
                var rhc = new RecruitHeroesSelectedCommand();
                rhc.HeroIds.Add(SelectedHero.Hero.Id);

                var cmd = new SelectedCommand { RecruitHeroesCommand = rhc };

                return cmd;
            }
        }

        public void NextHero() {
            _selectedHeroIndex++;
            if (_selectedHeroIndex >= HeroCount) { _selectedHeroIndex = 0; }
            DisplayHero();
        }
    }
}
