#include "proc_mapa.h"
#include "jgame.h"
#include <stdio.h>

namespace mapa
{    
	namespace arounders
	{
		int orientacio_inicial {0};
		int totals {0};
		int necessaris {0};

		int arrivats {0};
		int eixits {0};
		int morts {0};
	}

	namespace accions
	{
		int parar {0};
		int cavar {0};
		int escalar {0};
		int perforar {0};
		int escalera {0};
		int pasarela {0};
		int corda {0};
	}

	int ini_x, ini_y;
	int fin_x, fin_y;
	int velocitat;

	draw::surface *mapa = nullptr;

	//SDL_Surface *boto;

	int contador;

    void carregar()
	{
		FILE *f = file::getFilePointer("mapes.txt");

		//const int fase = game::getConfig("fase");
		int val;
		do {
			fscanf(f, "LEVEL %i", &val);
		} while (val != game::getConfig("fase"));

		int tileset=0;
		fscanf(f, "tileset = %i", &tileset);
		fscanf(f, "orientacio = %i", &arounders::orientacio_inicial);
		fscanf(f, "arounders = %i", &arounders::totals);
		fscanf(f, "necessaris = %i", &arounders::necessaris);
		
		fscanf(f, "parar = %i", &accions::parar);
		fscanf(f, "cavar = %i", &accions::cavar);
		fscanf(f, "escalar = %i", &accions::escalar);
		fscanf(f, "perforar = %i", &accions::perforar);
		fscanf(f, "escalera = %i", &accions::escalera);
		fscanf(f, "pasarela = %i", &accions::pasarela);
		fscanf(f, "corda = %i", &accions::corda);

		fscanf(f, "inici = %i %i", &ini_x, &ini_y);
		fscanf(f, "final = %i %i", &fin_x, &fin_y);

		//int tilemap[200];
		//for (int y=0; y<10; ++y) for (int x=0; x<10; ++x) fscanf(f, "%i", &tilemap[x+y*20]);

		draw::surface *tiles = draw::loadSurface("tiles.gif");
		draw::setSource(tiles);

		if (mapa) draw::freeSurface(mapa);
		mapa = draw::createSurface(320, 200);
		draw::setDestination(mapa);

		for (int y=0; y<10; ++y)
			for (int x=0; x<10; ++x)
			{
				int tile; fscanf(f, "%i", &tile);
				if (tile > 0) draw::draw(x*16, y*16, 16, 16, (tile-1)*16, tileset*16);
			}

		draw::freeSurface(tiles);

		fclose(f);

		draw::surface *marcador = draw::loadSurface("marcador.gif");
		draw::setSource(marcador);
		draw::draw(0, 165, marcador->w, marcador->h, 0, 0);
		draw::freeSurface(marcador);


	}

	char *formatejar(int numero);

    void pintar(int accio, int prevista);
	int procesar(int mousex, int mousey);

    void setAroundersNum(const int orient, const int total, const int necessaris);
    void setActions(const int parar, const int cavar, const int escalar, const int perforar, const int escalera, const int pasarela, const int corda);

}