#include "MapManager.h"
#include <fstream>
#include <string>

using namespace std;

MapManager::MapManager(void)
{
	mapOfTiles = 0;
	width = 0;
	height = 0;
}

MapManager::~MapManager(void)
{
	if ( mapOfTiles ) {
		// TODO: check if we need to loop over x's deleting y's
		delete mapOfTiles;
		mapOfTiles = 0;
	}
}

HRESULT MapManager::loadMap( char* mapFile ) {
	unloadMap();

	int mapFileLength = ( int ) strlen( mapFile );

	// Load tiles
	int tilePathLength = mapFileLength + 6 + 1;
	char* tilePath = ( char* ) malloc( sizeof( char ) * tilePathLength );
	ZeroMemory( tilePath, sizeof( tilePath ) );
	tilePath = strcat( tilePath, mapFile );
	tilePath = strcat( tilePath, ".tiles" );

	ifstream tileInput( tilePath );

	tileInput >> width;
	tileInput >> height;

	mapOfTiles = new int*[ width ];
	for ( int i = 0; i < width; i++ ) {
		mapOfTiles[ i ] = new int[ height ];
	}

	for ( int i = 0; i < height; i++ ) {
		for ( int j = 0; j < width; j++ ) {
			if ( tileInput.peek() != -1 ) {
				tileInput >> mapOfTiles[ j ][ i ];
			} else {
				GameError( "Error reading in map file: " );
				GameError( mapFile );
				return E_FAIL;
			}
		}
	}

	if ( tileInput.peek() != -1 ) {
		GameError( "Error reading in tiles.  Did not reach end of map file" );
	}

	if ( tilePath != NULL ) {
		delete tilePath;
		tilePath = NULL;
	}

	/*
	ofstream output( "files/output.txt" );
	for ( int i = 0; i < height; i++ ) {
		for ( int j = 0; j < width; j++ ) {
			output << mapOfTiles[ j ][ i ];
		}
		output << "\n";
	}
	*/

	return S_OK;
}

int MapManager::getTextureId( int x, int y ) {
	int textureId = -1;

	if ( mapOfTiles != 0 ) {
		if ( x >= 0 && x < width &&
			 y >= 0 && y < height ) {
			textureId = mapOfTiles[ x ][ y ];
		}
	}

	return textureId;
}

void MapManager::unloadMap() {
	for ( int i = 0; i < width; i++ ) {
		delete[] mapOfTiles[ i ];
	}
	if ( mapOfTiles ) {
		delete[] mapOfTiles;
		mapOfTiles = 0;
	}

	width = 0;
	height = 0;
}

void MapManager::printMap() {
	for ( int i = 0; i < height; i++ ) {
		for ( int j = 0; j < width; j++ ) {
			GameError( mapOfTiles[ j ][ i ] );
		}
	}
}

int MapManager::getWidth() {
	return width;
}

int MapManager::getHeight() {
	return height;
}
