using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class MapController : MonoBehaviour
{
    private MapLoader mapLoader;
    private MapData mapData;

    public delegate void MapCompleteDelegate(int score);
    public static event MapCompleteDelegate mapCompleteDelegate = null;

    private IEnumerator Start()
    {
        mapLoader = GetComponent<MapLoader>();
        mapLoader.LoadMapData(Constants.currentLevel);

        while (!mapLoader.GetIsReady())
            yield return null;

        StartMap();
    }

    void StartMap()
    {
        mapData = mapLoader.GetMapList();
        Debug.Log(mapData);

        GetComponent<DisplayMap>().SetData(mapData);
        GetComponent<MovementController>().SetData(mapData);

        MovementController.movementCompleteDelegate += MovementCompleteListener;
    }

    void OnDestroy ()
    {
        MovementController.movementCompleteDelegate -= MovementCompleteListener;
    }

    private void MovementCompleteListener()
    {
        Constants.currentLevel += 1;
        StartCoroutine(LoadNextLevel());
    }

    public IEnumerator LoadNextLevel()
    {
        yield return new WaitForSeconds(Constants.SIGN_DURATION);

        var sceneName = "Level";
        if (Constants.currentLevel > Constants.maxLevel)
            sceneName = "Lobby";
        
        Application.LoadLevel(sceneName);
    }
}