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

public class LevelGenerator : MonoBehaviour {
	public int numRows;
	public int numCols;
	public float tileSize = 1.44f;
	public Vector3 startPos;
	public GameObject wallTL;
	public GameObject wallT;
	public GameObject walls;
	
	void Start () {
		//Later: Take in a bigass array of integers to represent the tiles.
		
		//For now, create a dummy array.
		/*int[,] tileIntsArray = new int[numCols,numRows];
		for (int i = 0; i < numCols; i++) {
			for (int j = 0; j < numRows; j++) {
				int whichTile = Random.Range(0,3);
				tileIntsArray[i,j] = whichTile; //Unity is stupid... this is 0 or 1 or 2
			}
		}*/
		
		string[,] tileIntsArray = new string[numCols,numRows];
		string[] lines = System.IO.File.ReadAllLines(@"assets\level.txt");
		int curRow = 0;
		//grab line from file
		for (int cntr = lines.Length - 1; cntr >= 0; cntr += -1) {
			//create array
			string[] items = lines[cntr].Split('\t');
			//loop as many times as the length of array
			for (int j = 0; j < numCols; j++) {
				tileIntsArray[j,curRow] = items[j]; // Here's your integer. int.Parse()
			}
			curRow++;

		}
		
		
		//var innerWalls = new GameObject("innerWalls");
		
		//Now iterate through this array and spawn tiles.
		for (int i = 0; i < numCols; i++) {
			for (int j = 0; j < numRows; j++) {
				
				
				GameObject whichPrefab = null;
				float rotation = 0;
				switch (tileIntsArray[i,j]) {
				case "0":
					break;
				case "1":
					whichPrefab = wallTL;
					break;
				case "2":
					whichPrefab = wallTL;
					rotation = 90;
					break;
				case "3":
					whichPrefab = wallTL;
					rotation = 270;
					break;
				case "4":
					whichPrefab = wallTL;
					rotation = 180;
					break;
				case "5":
					whichPrefab = wallT;
					break;
				case "6":
					whichPrefab = wallT;
					rotation = 90;
					break;
				case "7":
					whichPrefab = wallT;
					rotation = 180;
					break;
				case "8":
					whichPrefab = wallT;
					rotation = 270;
					break;
				}
				
				if (whichPrefab != null) {
					GameObject newTile = (GameObject) Instantiate(whichPrefab);
					newTile.transform.parent = walls.transform;
					newTile.transform.rotation = newTile.transform.parent.rotation;
					newTile.transform.RotateAround(transform.position,Vector3.up,rotation);
					newTile.transform.localPosition = startPos + new Vector3(tileSize*i, tileSize*j, 0);
					//newTile.transform.rotation = Quaternion.identity;
				}
			}
		}
		
	}
}
