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

namespace eagle {
    using BattalionId = Int32;

    public class BattalionDropdownController : MonoBehaviour {
        private List<BattalionView> _availableBattalions;
        public List<BattalionView> AvailableBattalions {
            get => _availableBattalions;
            set {
                _availableBattalions = new List<BattalionView>(value);

                var dropdown = GetComponent<TMP_Dropdown>();

                dropdown.ClearOptions();
                dropdown.AddOptions(new List<TMP_Dropdown.OptionData> { new() { text = "None" } });
                dropdown.AddOptions(AvailableBattalions.Select(BattalionOption).ToList());
                dropdown.value = Math.Min(1, AvailableBattalions.Count);
            }
        }

        public BattalionId? SelectedBattalionId {
            get => GetComponent<TMP_Dropdown>().value == 0
                           ? null
                           : AvailableBattalions[GetComponent<TMP_Dropdown>().value - 1].Id;
            set => GetComponent<TMP_Dropdown>().value =
                    AvailableBattalions.FindIndex(h => h.Id == value) + 1;
        }

        public UnityEvent SelectedBattalionIdUpdated;

        public void DropdownUpdated(int newValue) {
            gameObject.GetComponentInParent<EagleGameController>()
                    .GetComponentInChildren<HeroesAndBattalionsPanelController>()
                    .UpdateBattalionSelections();

            if (SelectedBattalionIdUpdated != null) SelectedBattalionIdUpdated.Invoke();
        }

        private TMP_Dropdown.OptionData BattalionOption(BattalionView bv) {
            var texture =
                    gameObject.GetComponentInParent<EagleCommonTextures>().BattalionType(bv.Type);
            return new TMP_Dropdown.OptionData {
                image = Sprite.Create(
                        texture,
                        new Rect(0, 0, texture.width, texture.height),
                        new Vector2(0.5f, 0.5f)),
                text = $"{bv.Name} ({bv.Size})"
            };
        }
    }
}
