﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MapManager : MonoBehaviour
{
  public Tile[,] Tiles;
  public List<Mob> Mobs;
	
	void Start ()
  {
    BuildMap();
  }

  void BuildMap()
  {
    int xMax = 0;
    int xMin = 0;
    int yMin = 0;
    int yMax = 0;
    List<Transform> children = new List<Transform>();
    Mobs = new List<Mob>();
    for (int i = 0; i < transform.childCount; ++i)
    {
      //Debug.Log(transform.GetChild(i).name);
      children.Add(transform.GetChild(i));
      if ((int)children[i].transform.position.x < xMin)
      {
        xMin = (int)children[i].transform.position.x;
        //Debug.Log("xMin = " + xMin);
      }
      if ((int)children[i].transform.position.x > xMax)
      {
        xMax = (int)children[i].transform.position.x;
        //Debug.Log("xMax = " + xMax);
      }
      if ((int)children[i].transform.position.z < yMin)
      {
        yMin = (int)children[i].transform.position.z;
        //Debug.Log("yMin = " + yMin);
      }
      if ((int)children[i].transform.position.z > yMax)
      {
        yMax = (int)children[i].transform.position.z;
        //Debug.Log("yMax = " + yMax);
      }
      //assumes anything on tile is a mob
      if (transform.GetChild(i).childCount > 0)
      {
        Mob mob = transform.GetChild(i).GetComponentInChildren<Mob>();
        //Mob mob = transform.GetChild(i).GetChild(0).GetComponent<Mob>();
        if (mob != null)
        {
          Mobs.Add(mob);
        }
      }
    }
    Tiles = new Tile[xMax + Mathf.Abs(xMin) + 1, yMax + Mathf.Abs(yMin) + 1];
    foreach (Transform child in children)
    {
      Tile tile = child.GetComponent<Tile>();
      int x = (int)child.position.x + Mathf.Abs(xMin);
      int y = (int)child.position.z + Mathf.Abs(yMin);
      Tiles[x, y] = tile;
      Tiles[x, y].x = x;
      Tiles[x, y].y = y;
      child.name = x.ToString() + "/" + y.ToString();

    }
    foreach(Mob mob in Mobs)
    {
      //Debug.Log(mob.name);
      mob.x = mob.transform.parent.GetComponent<Tile>().x;
      mob.y = mob.transform.parent.GetComponent<Tile>().y;
      //Debug.Log(mob.name + "x" + mob.x + " y" + mob.y);
    }
  }
}
