using System;
using System.Collections.Generic;
using eagle;
using Net.Eagle0.Eagle.Api;
using Net.Eagle0.Eagle.Common;
using Net.Eagle0.Eagle.Views;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using Random = System.Random;

public class AvailableGameItem : MonoBehaviour {
    public GameObject item;
    public TextMeshProUGUI gameIdField;
    public HeroDropdownController heroDropdownController;
    public TextMeshProUGUI playerCountField;
    public Button joinButton;
    public TextMeshProUGUI buttonText;

    public Action<long, string> JoinCallback;

    private List<AvailableLeader> availableLeaders;
    private long gameId;

    public string SelectedLeaderTextId {
        get {
            if (heroDropdownController.SelectedHeroId == 0) {
                var index = new Random().Next(availableLeaders.Count);
                return availableLeaders[index].NameTextId;
            } else {
                return availableLeaders[heroDropdownController.SelectedHeroId - 1].NameTextId;
            }
        }
    }

    // Use this for initialization
    void Start() {}

    public void JoinClicked() { JoinCallback(gameId, SelectedLeaderTextId); }

    public void
    SetAvailableNewGame(long gameId, string playersString, List<AvailableLeader> leaders) {
        availableLeaders = leaders;
        this.gameId = gameId;

        gameIdField.text = string.Format("{0:X}", gameId);
        playerCountField.text = playersString;
        joinButton.interactable = true;
        buttonText.text = "JOIN";

        List<HeroView> heroOptions =
                new List<HeroView> { new() { Id = 0, Profession = Profession.NoProfession } };
        for (int i = 0; i < leaders.Count; i++) {
            var leader = leaders[i];
            heroOptions.Add(new HeroView {
                NameTextId = leader.NameTextId,
                Profession = leader.Profession,
                Id = i + 1
            });
        }

        heroDropdownController.FallbackText = "Random";
        heroDropdownController.AvailableHeroes = heroOptions;
    }
}
