using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class MapLoader : MonoBehaviour
{
    private bool isReady = false;
	private MapData mapData;

    public void LoadMapData(int index = 0)
    {
        // string filename = string.Format("map_{0}.json", name);
        string filename = string.Format("map_level_{0,3:D3}.json", index);
        string filePath = Path.Combine(Application.streamingAssetsPath, filename);
        
        Debug.Log("Loading Map - filePath " + filePath);
        WWW request = new WWW(filePath);
        
        StartCoroutine(WaitForRequest(request));
    }

    IEnumerator WaitForRequest(WWW request)
    {
        yield return request;

        if (request.error == null)
        {
            string dataAsJson = request.text;

            MapData loadedData = JsonUtility.FromJson<MapData> (dataAsJson);

			mapData = loadedData;
            mapData.SetTiles();

            Debug.Log ("Data loaded, list contains: " + mapData + " entries");
        }
        else 
            Debug.LogError ("Cannot load map file!");

        isReady = true;
    }

    public MapData GetMapList()
    {
        if (mapData != null)
            return mapData;
		else 
            Debug.LogError ("No map loaded!");

		return null;
    }

    public bool GetIsReady()
    {
        return isReady;
    }
}