package holo.bolt.world.map;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

import holo.bolt.world.map.tile.Tile;

public abstract class Level
{
	public int[][] idTable;
	public ArrayList<Integer[]> entities;
	
	public void initLevel()
	{
		idTable = getIdTable();
		entities = getEntities();
	}
	
	public int getIdFromCoords(int y, int x)
	{
		return idTable[y][x];
	}
	
	public int getWidth()
	{
		return getSize()[0] * Tile.size;
	}
	
	public int getHeight()
	{
		return getSize()[1] * Tile.size;
	}
	
	public int[] getSize()
	{
		int[][] tab = getIdTable();
		int[] len = new int[2];
		len[0] = tab[0].length;
		len[1] = tab.length;
		return len;
	}
	
	public int[][] getIdTable()
	{
		try
		{
			File file = new File(getTileLocation());
			if (!file.exists())
			{
				System.out.println("No file at " + getTileLocation());
				return null;
			}

			ArrayList<List<Integer>> ids = new ArrayList<List<Integer>>();
			
			Scanner sc = new Scanner(file);
			while(sc.hasNext())
			{
				String data = sc.nextLine();
				String[] datums = data.split(" ");
				List<String> datumList = Arrays.asList(datums);
				ArrayList<Integer> idList = new ArrayList<Integer>();
				Iterator<String> iter = datumList.iterator();
				while(iter.hasNext())
				{
					idList.add(Integer.valueOf(iter.next()));
				}
				ids.add(idList);
			}
			int[][] tileTable = new int[ids.size()][ids.get(0).size()];
			for(int i = 0; i < ids.size(); ++i)
			{
				for(int j = 0; j < ids.get(i).size(); ++j)
				{
					tileTable[i][j] = ids.get(i).get(j);
				}
			}

			sc.close();
			return tileTable;
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		
		return null;
	}
	
	public ArrayList<Integer[]> getEntities()
	{
		try
		{
			File file = new File(getEntityLocation());
			if (!file.exists())
			{
				System.out.println("No file at " + getEntityLocation());
				return null;
			}

			ArrayList<Integer[]> entities = new ArrayList<Integer[]>();
			
			Scanner sc = new Scanner(file);
			while(sc.hasNext())
			{
				entities.add(new Integer[] {sc.nextInt(), sc.nextInt(), sc.nextInt()});
			}

			sc.close();
			return entities;
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		
		return null;
	}
	
	public abstract String getTileLocation();
	
	public abstract String getEntityLocation();
}
