#include "Map.h"
#include <Utils/Size2D.h>
#include <Utils/Point2D.h>
#include <Widgets/WidgetRegistry.h>

namespace graphics
{
	Map *Map::currentMap;
	gge::utils::Size Map::screenSize;
	gge::graphics::Colorizable2DLayer Map::baseLayer;
	gge::graphics::Colorizable2DLayer Map::tileLayer;
	gge::graphics::Colorizable2DLayer Map::objectLayer;
	gge::graphics::Colorizable2DLayer Map::fogLayer;
	gge::graphics::Colorizable2DLayer Map::overlayer;
	gge::animation::Basic2DAnimation *Map::artisanicon; 
	gge::animation::Basic2DAnimation *Map::soldiericon;

	Map::Map(assets::Map &given_provider): provider(given_provider), scrollPoint(0,0), 
		showBuildable(false), buildingFloaterAnim(NULL), showAsNonBuildable(false)
	{
		zoomAmount = TILE_SIZE;

		gge::utils::Size mapSize = provider.tileMap.GetSize();
		tileMap.Resize(mapSize);

		baseLayer.BoundingBox.SetSize(mapSize.Width * zoomAmount, mapSize.Height * zoomAmount);
		tileLayer.BoundingBox.SetSize(mapSize.Width * zoomAmount, mapSize.Height * zoomAmount);
		objectLayer.BoundingBox.SetSize(mapSize.Width * zoomAmount, mapSize.Height * zoomAmount);
		fogLayer.BoundingBox.SetSize(mapSize.Width * zoomAmount, mapSize.Height * zoomAmount);
		overlayer.BoundingBox.SetSize(mapSize.Width * zoomAmount, mapSize.Height * zoomAmount);

		tileMap.ForAllCells([&] (const gge::utils::Point &index, Tile &tile)
		{
			tile.initialize(*(provider.tileMap(index)), timer);
		});

		selectionDrawing=&gge::widgets::WR.Borders.Selection->CreateAnimation(true);
		topSelection=&gge::widgets::WR.Borders.Focus->CreateAnimation(true);
		loggerFont=gge::widgets::WR.Fonts.Normal;
		loggerShadow=gge::widgets::WR.Fonts.Normal;
		loggerShadow.Color=0xff000000;
	}

	void Map::initialize(const gge::utils::Size &screenSize)
	{
		currentMap = NULL;
		baseLayer.Add(tileLayer, 3);
		baseLayer.Add(objectLayer, 2);
		baseLayer.Add(overlayer, 1);
		baseLayer.Add(fogLayer, 0);
		Map::screenSize = screenSize;

		fogAnim=new Animation(*assets::AnimationProvider::list["_fog"]);
		unchartedAnim=new Animation(*assets::AnimationProvider::list["_uncharted"]);

		artisanicon=&gge::widgets::WR.Icons("artisan");
		soldiericon=&gge::widgets::WR.Icons("soldier");
	}

	void Map::scrollTo(const gge::utils::Point &location) 
	{
		scrollPoint = location;

		scrollPoint.x=gge::utils::Limit(scrollPoint.x, 0, tileMap.GetWidth() * zoomAmount - screenSize.Width);
		scrollPoint.y=gge::utils::Limit(scrollPoint.y, 0, tileMap.GetHeight() * zoomAmount - screenSize.Height);

		baseLayer.BoundingBox.MoveTo(-scrollPoint);
	}

	void Map::scrollBy(const gge::utils::Point &scrollAmount)
	{
		scrollTo(scrollPoint + scrollAmount);
	}
}
