#include "ai.h"

BEGIN_TEG_NAMESPACE();

namespace ai {

//void C::floodFill(Tablero& t) {
//
//}


Tablero::Tablero() : numberOfRows(TABLERO_NRO_ROWS), numberOfColumms(TABLERO_NRO_COLS) {
	for (int i = 0; i < numberOfRows; ++i)
		for (int j = 0; j < numberOfColumms; ++j)
			state[i][j] = EMPTY;
}

Tablero::~Tablero() { }

void Tablero::growBorder() {

	int newTablero[TABLERO_NRO_ROWS][TABLERO_NRO_COLS];

	for(int i=0; i<TABLERO_NRO_ROWS; ++i) {
		for(int j=0; j<TABLERO_NRO_COLS; ++j) {

			bool wall = (state[i][j] == WALL);
			if(!wall) {
				for(int dx=-5; dx<=5; ++dx) {
					for(int dy=-5; dy<=5; ++dy) {
						if(state[i+dy][j+dx] == WALL)
							wall = true;
					}
				}
			}

			newTablero[i][j] = wall ? WALL : EMPTY;
		}
	}

	memcpy(state, newTablero, sizeof(state));
}

void Tablero::saveMap() {
	FILE* f = fopen("newTablero.txt", "w");
	for(int i=0; i<numberOfRows; ++i) {
		for(int j=0; j<numberOfColumms; ++j) {
			fprintf(f, "%d ", state[i][j]);
		}
		fprintf(f, "\n");
	}
	fclose(f);
}

void Tablero::loadMap(const char *filename) {
	FILE* f = fopen(filename, "r");
	for(int i=0; i<numberOfRows; ++i) {
		for(int j=0; j<numberOfColumms; ++j) {
			int isWall;
			fscanf(f, "%d", &isWall);
			if(isWall) state[i][j] = WALL;
		}
	}
	fclose(f);

	growBorder();
	saveMap();
}


void Tablero::restore() {
	for (int i = 0; i < numberOfRows; ++i) {
		for (int j = 0; j < numberOfColumms; ++j) {
			state[i][j] &= ~MARK;
			if(state[i][j] == 0) state[i][j] = EMPTY;
		}
	}
}

//math::Vec2<int> GetPosition(std::map< math::Vec2<int>, math::Vec2<int> > prev, math::Vec2<int> pos) {
math::Vec2<int> GetPosition(std::map< std::pair<int, int>, std::pair<int, int> > prev, std::pair<int, int> pos) {

	//int a = prev.count(pos);
	std::pair<int, int> ant = pos;
	while (prev.count(pos)) ant = pos, pos = prev[pos];
	return math::Vec2<int>(ant.first, ant.second);

}

std::vector< math::Vec2<int> > GetPath(std::map< std::pair<int, int>, std::pair<int, int> > prev, std::pair<int, int> pos) {
	std::vector< math::Vec2<int> > sol;
	sol.push_back(math::Vec2<int>(pos.first, pos.second));
	while (prev.count(pos)) pos = prev[pos], sol.push_back(math::Vec2<int>(pos.first, pos.second));
	sol.pop_back();
	return sol;
}



};

END_TEG_NAMESPACE();
