using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class LevelLoader : MonoBehaviour {
    public GameObject gameWorld;
    public GameObject loadLevelButtonPrefab;

    private GameObject loadLevelUi;

    public void Start()
    {
        loadLevelUi = GameObject.Find("Load Level Panel");
        loadLevelUi.SetActive(false);
    }

    public void Update() {
        if (Input.GetKeyDown(KeyCode.L) && Input.GetKey(KeyCode.LeftAlt))
        {
            CreateButtons();
            loadLevelUi.SetActive(!loadLevelUi.activeInHierarchy);
        }
    }

    public void Load(string name)
    {
        LevelList list = LevelList.LoadFromFile();

        LevelData level = list.gameLevels.Find(l => l.levelName == name);
        if(level == null) {
            level = list.userLevels.Find(l => l.levelName == name);
        }

        if (level == null)
        {
            return;
        }

        foreach (Transform transform in gameWorld.transform)
        {
            Destroy(transform.gameObject);
        }

        foreach (LevelElement element in level.elements)
        {
            GameObject prefab = Resources.Load(element.prefab) as GameObject;
            GameObject obj = Instantiate(prefab, element.position, element.rotation, gameWorld.transform) as GameObject;
            obj.transform.localScale = element.scale;
            obj.GetComponent<SerializableElement>().AfterLoad(element);
        }

        loadLevelUi.SetActive(false);
    }

    private void CreateButtons()
    {
        foreach (Transform transform in loadLevelUi.transform)
        {
            Destroy(transform.gameObject);
        }

        LevelList list = LevelList.LoadFromFile();
        foreach (LevelData level in list.gameLevels)
        {
            Button button = Instantiate(loadLevelButtonPrefab).GetComponent<Button>();
            button.transform.SetParent(loadLevelUi.transform, false);
            button.name = level.levelName;
            button.GetComponentInChildren<Text>().text = level.levelName;
        }

        foreach (LevelData level in list.userLevels)
        {
            Button button = Instantiate(loadLevelButtonPrefab).GetComponent<Button>();
            button.transform.SetParent(loadLevelUi.transform, false);
            button.name = level.levelName;
            button.GetComponentInChildren<Text>().text = level.levelName;
        }
    }
}
