﻿using UnityEngine;
using System.Collections;

public class TreeGen : MonoBehaviour {

	int treesNumber; //Количество деревьев, которые разместятся на карте
	int width;
	int height;
	float treeSize; //Коэффициент размера

	public int[,] mapTrees;
	int treesNumberMax; //Количество деревьев, которые можно расположить на карте

	public CaveGeneration cave;

	// Use this for initialization
	void Start () {
	
		mapTrees = cave.map;
		width = cave.width;
		height = cave.height;
		treeSize = cave.sizeOfSquare;

		PercentCount ();
		TreeGenerate ();
	}

	void PercentCount () {
		
		for (int x = 0; x < mapTrees.GetLength (0); x++)
			for (int z = 0; z < mapTrees.GetLength (1); z++) {
				
				if ((mapTrees [x, z] == 0) && (mapTrees [x + 1, z] == 0) && (mapTrees [x - 1, z] == 0) &&
				    (mapTrees [x, z + 1] == 0) && (mapTrees [x + 1, z + 1] == 0) && (mapTrees [x - 1, z + 1] == 0) &&
				    (mapTrees [x, z - 1] == 0) && (mapTrees [x + 1, z - 1] == 0) && (mapTrees [x - 1, z - 1] == 0)) {
				
					treesNumberMax++;
				}

			}
		
		treesNumber = (int)treesNumberMax / 10;
	}

	void TreeGenerate () {

		for (int i = 0; i < treesNumber; i++) {

			int xCoor = Random.Range (0, mapTrees.GetLength (0));
			int zCoor = Random.Range (0, mapTrees.GetLength (1));

			if ((mapTrees [xCoor, zCoor] == 1) && (i > 0))
				i--;

			if ((mapTrees [xCoor, zCoor] == 0) && (mapTrees [xCoor + 1, zCoor] == 0) && (mapTrees [xCoor - 1, zCoor] == 0) &&
			    (mapTrees [xCoor, zCoor + 1] == 0) && (mapTrees [xCoor + 1, zCoor + 1] == 0) && (mapTrees [xCoor - 1, zCoor + 1] == 0) &&
			    (mapTrees [xCoor, zCoor - 1] == 0) && (mapTrees [xCoor + 1, zCoor - 1] == 0) && (mapTrees [xCoor - 1, zCoor - 1] == 0)) {

				GameObject tree = (GameObject) Instantiate (Resources.Load("Tree"), new Vector3 (-width / 4 + xCoor * treeSize + 0.5f, -0.5f, -height / 4 + zCoor * treeSize + 0.5f), transform.rotation);
				tree.transform.localScale = new Vector3 (tree.transform.localScale.x * treeSize, tree.transform.localScale.y * treeSize, tree.transform.localScale.z * treeSize);
				mapTrees [xCoor, zCoor] = 1;

				cave.map [xCoor, zCoor] = 2;
				cave.map [xCoor + 1, zCoor] = 2;
				cave.map [xCoor - 1, zCoor] = 2;
				cave.map [xCoor, zCoor + 1] = 2;
				cave.map [xCoor, zCoor - 1] = 2;
				cave.map [xCoor + 1, zCoor + 1] = 2;
				cave.map [xCoor + 1, zCoor - 1] = 2;
				cave.map [xCoor - 1, zCoor + 1] = 2;
				cave.map [xCoor - 1, zCoor - 1] = 2;
			}

		}
	}

}
