using System;
using common;
using EagleGUIUtils;
using Net.Eagle0.Eagle.Views;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace eagle {
    using FactionId = Int32;

    public class HeroDetailsController : MonoBehaviour {
        public RawImage headshotImage;
        public RawImage professionImage;
        public GeneratedTextUpdater heroNameTextUpdater;
        public TMP_Text strengthText;
        public TMP_Text agilityText;
        public TMP_Text vigorText;
        public TMP_Text charismaText;
        public TMP_Text wisdomText;

        public RawImage archeryImage;
        public RawImage fireImage;

        public GameObject vipImageContainer;
        public Image factionColorImage;

        private string StatView(int value) {
            if (value == 0) return "??";
            return value.ToString();
        }

        public string StatView(double value) { return StatView((int)value); }

        private void SetHeroBasics(HeroView value) {
            if (value.ImagePath is String imagePath && !string.IsNullOrEmpty(imagePath)) {
                ResourceFetcher.headshotFetcher.LoadIntoRawImage(headshotImage, value.ImagePath);
            }
            professionImage.texture =
                    gameObject.GetComponentInParent<EagleCommonTextures>().Profession(
                            value.Profession);
            professionImage.gameObject.SetActive(professionImage.texture != null);
            professionImage.gameObject.GetComponent<HoveringTooltipTextProvider>().text =
                    DisplayNames.ProfessionNames[value.Profession];

            heroNameTextUpdater.TextId = value.NameTextId;
            strengthText.text = StatView(value.Strength);
            agilityText.text = StatView(value.Agility);
            vigorText.text =
                    $"{GUIUtils.ConditionString(value.Vigor)}/{StatView(value.Constitution)}";
            charismaText.text = StatView(value.Charisma);
            wisdomText.text = StatView(value.Wisdom);

            archeryImage.gameObject.SetActive(value.ArcheryCapable);
            fireImage.gameObject.SetActive(value.StartFireCapable);
        }

        private void SetOrdinaryHero(HeroView value) {
            SetHeroBasics(value);

            vipImageContainer.gameObject.SetActive(false);

            factionColorImage.color = Color.clear;
        }

        private void SetFactionLeader(HeroView value, Color factionColor) {
            SetOrdinaryHero(value);
            vipImageContainer.gameObject.SetActive(true);

            factionColorImage.color = factionColor;
        }

        public void SetHero(HeroView hero, IGameModel model) {
            if (hero.FactionId is FactionId fid &&
                model.ActiveFactions[fid].Leaders.Contains(hero.Id)) {
                SetFactionLeader(hero, PlayerColors.LightPlayerColor(fid));
            } else {
                SetOrdinaryHero(hero);
            }
        }
    }
}