using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;

public class DisplayScrolls : MonoBehaviour
{
    public string preferredStartScrollName;

    static public List<REST_JSON_API.Scroll> AllowedScrolls;
    public GameObject[] ScrollButtons;
    public GameObject ScrollPrefab;
    public GameObject DetailScreen;

    public Transform scrollscreenContent;

    void Awake()
    {
        BuildScrollGUI();
    }

    void BuildScrollGUI()
    {
        while (GlobalBehaviour.InitiateScrolls.MoveNext()) ; // active wait for server, should be rare

        AllowedScrolls = StageStatic.stage?.AllowedScrolls == null
            ? GlobalBehaviour.AvailableScrolls
            : GlobalBehaviour.AvailableScrolls
                .Where(s => StageStatic.stage.AllowedScrolls.Contains(s.ScrollReference))
                .ToList();

        //Build Selection-GUI of Scrolls
        ScrollButtons = new GameObject[AllowedScrolls.Count()];
        for (int i = 0; i < AllowedScrolls.Count; i++)
        {
            var obj = Instantiate(ScrollPrefab, scrollscreenContent);
            obj.GetComponent<ScrollClickedScript>().scroll = AllowedScrolls[i];
            obj.GetComponent<ScrollClickedScript>().DetailScreen = this.DetailScreen;
            obj.transform.GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = AllowedScrolls[i].label;
            ScrollButtons[i] = obj;
        }

        REST_JSON_API.Scroll preferredStartScroll = AllowedScrolls.Find(x => x.label.Equals(preferredStartScrollName));
        if (preferredStartScroll != null)
            ScrollDetails.Instance?.SetScroll(preferredStartScroll);
    }
}