#include <SDL.h>
#include <stdio.h>
#include <stdlib.h>

#include "engine.h"

Dp Dp::Init()
{
	if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
	{
		Crash( "SDL could not initialize");
	}

	SDL_Window* window = SDL_CreateWindow( "title", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH*SCREEN_SCALE, SCREEN_HEIGHT*SCREEN_SCALE, SDL_WINDOW_SHOWN );
	if( window == NULL )
	{
		Crash( "Window could not be created" );
	}
	SDL_SetHint (SDL_HINT_RENDER_SCALE_QUALITY, 0);
	SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED );
	if( renderer == NULL )
	{
		Crash( "Renderer could not be created" );
	}
	SDL_SetRenderDrawColor( renderer, 0x00, 0x00, 0x00, 0x00 );
	SDL_RenderSetIntegerScale(renderer, SDL_TRUE);
	SDL_RenderSetLogicalSize(renderer, SCREEN_WIDTH, SCREEN_HEIGHT);

	Dp dp = Dp();
	dp.renderer = renderer;
	dp.window = window;
	dp.rects = new SDL_Rect[100];

	dp.Btns = new char[SumBtns];
	for(int i=0;i<SumBtns;i++) dp.Btns[i] = 0;

	dp.textures = new SDL_Texture*[SumImages];
	for(int i=0;i<SumImages;i++)
	{
		dp.LoadImage(i, ImagePath(i));
	}

	return dp;
}



void Crash(char* msg)
{
	printf("error : %s ! %s \n", msg, SDL_GetError());
	SDL_Quit();
	exit(0);
}
void Dp::LoadImage(int image, const char* path)
{
	printf("loading %s\n",path);
	SDL_Surface* surface = SDL_LoadBMP(path);
	if (!surface)
	{
		Crash( "Unable to load");
	}
	SDL_SetColorKey(surface, SDL_TRUE,  SDL_MapRGB( surface->format,0xDE, 0xAD, 0xBE ) );
	SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
	if (!texture)
	{
		Crash( "Unable to create texture");
	}
	SDL_SetTextureBlendMode( texture, SDL_BLENDMODE_BLEND);
	SDL_FreeSurface(surface);
	this->textures[image] = texture;
}

SDL_Rect GetRect(SDL_Texture* texture)
{
	SDL_Rect rect;
	rect.x = 0;
	rect.y = 0;
	Uint32 f;
	int a;
	SDL_QueryTexture(texture,&f,&a,&rect.w,&rect.h);
	return rect;
}

SDL_Rect IntersectRect(SDL_Rect first, SDL_Rect second)
{
	SDL_Rect intersect = {0,0,0,0};
	SDL_IntersectRect(&first,&second,&intersect);
	return intersect;
}


void Dp::Blit(int image, int x, int y)
{
	SDL_Texture* texture = this->textures[image];
	SDL_Rect size = GetRect(texture);
	SDL_Rect screen = {0,0,SCREEN_WIDTH, SCREEN_HEIGHT};
	SDL_Rect pos =
	{
		x + (SCREEN_WIDTH/2) - (size.w/2) - this->X,
		y + (SCREEN_HEIGHT/2) - (size.h/2) - this->Y,
		size.w,
		size.h
	};
	SDL_Rect intersect = IntersectRect(screen, pos);
	if (intersect.w <= 0) return;
	if (intersect.h <= 0) return;
	SDL_Rect dest =
	{
		pos.x > 0 ? pos.x : 0,
		pos.y > 0 ? pos.y : 0,
		intersect.w,
		intersect.h
	};
	SDL_Rect src =
	{
		pos.x < 0 ? abs(pos.x) : 0,
		pos.y < 0 ? abs(pos.y) : 0,
		intersect.w,
		intersect.h
	};
	SDL_RenderCopy(this->renderer, texture, &src, &dest);
}

