/*
 * Map.cpp
 *
 *  Created on: Feb 13, 2020
 *      Author: ayoungblood
 */

#include "Map.h"
#include "../game/Game.hpp"
#include <fstream>
#include "../ecs/ECS.h"
#include "../ecs/Components.h"
#include <string>
#include <iostream>

extern Manager manager;

Map::Map(std::string tID, int ms, int ts) : texID(tID), mapScale(ms), tileSize(ts)
{
	scaledSize = ms* ts;
	width = 0;
	height = 0;
	tSize = ts;
}

Map::~Map()
{
}

void Map::LoadMap(std::string path, int sizeX, int sizeY, int scale)
{
	char c;
	std::fstream mapFile;
	mapFile.open(path);
	int srcX, srcY;
    
	width = tSize*scale*sizeX;
	height = tSize*scale*sizeY;

	for (int y = 0; y < sizeY; y++)
	{
		for (int x = 0; x < sizeX; x++)
		{
			mapFile.get(c);
			srcY = atoi(&c) * tileSize;
			mapFile.get(c);
			srcX = atoi(&c) * tileSize;
			mapFile.ignore(2,',');
		}
	}

	mapFile.ignore();
// colliders
	for (int y =0; y < sizeY; y++)
	{
		for (int x = 0; x < sizeX; x++)
		{
			mapFile.get(c);
			if (c == '1')
			{
				auto& tcol(manager.addEntity());
                tcol.addComponent<ColliderComponent>("terrain",x*scaledSize,y*scaledSize,tileSize,scale,texID);
				tcol.addGroup(Game::groupColliders);
			}
			mapFile.ignore(2,',');
		}
	}
	mapFile.close();
}

void Map::AddTile(int srcX, int srcY, int xpos, int ypos)
{
	auto& tile(manager.addEntity());
	tile.addComponent<TileComponent>(srcX,srcY,xpos,ypos,tileSize, mapScale, texID);
	tile.addGroup(Game::groupMap);
}
