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

public class LevelSaver : MonoBehaviour {

    public GameObject gameWorld;

    private GameObject saveLevelUi;
    private GameObject saveLevelNameInputUi;

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

    public void Update()
    {
        if (Input.GetKeyDown(KeyCode.S) && Input.GetKey(KeyCode.LeftAlt))
        {
            saveLevelUi.SetActive(!saveLevelUi.activeInHierarchy);
        }
    } 

    public void SaveFromUi()
    {
        saveLevelNameInputUi = GameObject.Find("Level Name Input");
        InputField inputField = saveLevelNameInputUi.GetComponent<InputField>();
        Save(inputField.text);
    }

    public void Save(string name)
    {
        LevelData levelData = new LevelData();

        levelData.levelName = name;
        foreach (Transform childTransform in gameWorld.transform)
        {
            GameObject child = childTransform.gameObject;
            SerializableElement se = child.GetComponent<SerializableElement>();

            if (se != null)
            {
                LevelElement element = new LevelElement();
                element.position = childTransform.position;
                element.scale = childTransform.localScale;
                element.rotation = childTransform.rotation;
                element.prefab = se.prefabPath;
                se.GetComponent<SerializableElement>().BeforeSave(element);
                levelData.elements.Add(element);
            }
        }

        LevelList list = LevelList.LoadFromFile();
        list.AddUserLevel(levelData);
        list.SaveToFile();

        saveLevelUi.SetActive(false);
    }
}
