#include "const.h"
#include "map.h"

// Constructor
Map::Map(SDL_Renderer *renderer, LTexture *texture1, LTexture *texture2, LTexture *texture3, std::string file)
{
	init(renderer, texture1, texture2, texture3, file);
}

// Destructor
Map::~Map()
{
	delete sprite_tile;
	delete sprite_actor;
	delete background;
	sprite_tile = nullptr;
	sprite_actor = nullptr;
	background = nullptr;

	delete[] tile;
	delete[] actor;
}

// Inicializa todas las variables
void Map::init(SDL_Renderer *renderer, LTexture *texture1, LTexture *texture2, LTexture *texture3, std::string file)
{
	sprite_tile = new AnimatedSprite();
	sprite_tile->setTexture(texture1);
	sprite_tile->setRenderer(renderer);

	sprite_actor = new AnimatedSprite();
	sprite_actor->setTexture(texture2);
	sprite_actor->setRenderer(renderer);

	background = new Sprite();
	background->setTexture(texture3);
	background->setRenderer(renderer);
	background->setSpriteClip(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);

	src_rect = {0, 0, 0, 0};
	dst_rect = {0, 0, 0, 0};
	w = 0;
	h = 0;
	room = 0;

	loadFromFile(file);
}

// Carga el mapa a partir de un fichero
void Map::loadFromFile(std::string path)
{
	std::string filename = path.substr(path.find_last_of("\\/") + 1);
	SDL_RWops *file = SDL_RWFromFile(path.c_str(), "r+b");
	Uint8 *w;
	Uint8 *h;

	if (file == NULL)
	{
		printf("Warning: Unable to open %s file\n", filename.c_str());
	}
	else
	{
		printf("Reading file %s\n", filename.c_str());

		SDL_RWread(file, &w, sizeof(Uint8), 1);
		SDL_RWread(file, &h, sizeof(Uint8), 1);

		long size = (*w) * (*h);
		tile = new Uint8[size];
		actor = new Uint8[size];

		for (long i = 0; i < size; i++)
			SDL_RWread(file, &tile[i], sizeof(Uint8), 1);

		for (long i = 0; i < size; i++)
			SDL_RWread(file, &actor[i], sizeof(Uint8), 1);
		
		SDL_RWclose(file);
	}
}

// Resetea ciertas variables
void Map::reset()
{
}

// Actualiza todas las variables
void Map::update()
{
	background->setPosX(0);
	background->setPosY(0);
}

// Dibuja el objeto
void Map::render()
{
	background->render();
}