#include <SDL2/SDL.h>
#include <SDL2/SDL_video.h>
#include "config.h"
#include "font.h"

extern float displayScale;
int WINMODE = 0;

static SDL_Window *window;
static SDL_Renderer *renderer;
static SDL_Texture *texture;

void initWindow(){
    if (SDL_Init(SDL_INIT_VIDEO)){
        printf("Could not init SDL: %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }
    
    atexit(SDL_Quit);
    
    window = SDL_CreateWindow("LS7 Emulator", 
                              SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                              SDL_X_SIZE, SDL_Y_SIZE, WINMODE);
    if (window == NULL){
        printf("Fatal! Could not create SDL Window: %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }
    
    renderer = SDL_CreateRenderer(window, -1, 2);
    if (renderer == NULL){
        printf("Fatal! Could not create SDL Renderer: %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }
    
    texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
                                SDL_TEXTUREACCESS_STREAMING,
                                SDL_X_SIZE, SDL_Y_SIZE);
    if (texture == NULL){
        printf("Fatal! Could not create SDL Texture: %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }
    
    if (SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_NONE)){
        printf("Fatal! Could not set SDL blend mode: %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }
}

void sdlResize(){
    SDL_SetWindowSize(window, SDL_X_SIZE * displayScale, SDL_Y_SIZE * displayScale);
}

void clearScreen(uint32_t pixels[], uint32_t color){
    for (uint32_t i = 0; i < SDL_X_SIZE * SDL_Y_SIZE; i++) pixels[i] = color;
}

#define CHARMARGIN 0
void drawString(const char* string, uint32_t pixels[], uint16_t screenXsize, uint32_t foreground, uint32_t background, uint16_t x, uint16_t y, uint8_t scale){
	uint16_t xCount = x;
	uint16_t yCount = y;

	for (int i = 0; string[i]; i++){
		if (string[i] > 31 && string[i] < 127){
			for (int _x = 0; _x < FONT_WIDTH * scale; _x++){
				if (xCount + _x >= screenXsize){
					xCount = x;
					yCount += (FONT_HEIGHT + CHARMARGIN) * scale;
				}
				
				for (int _y = 0; _y < FONT_HEIGHT * scale; _y++){	
					uint8_t value = typeface[((string[i] - 32) * FONT_HEIGHT) + (_y / scale)] & (128 >> (_x / scale));
				if (value && foreground != 0) pixels[(( yCount + _y) * screenXsize) + (xCount + _x)] = foreground;
				else if (!value && background != 0) pixels[(( yCount + _y) * screenXsize) + (xCount + _x)] = background; 
				}
			}
			xCount += (FONT_WIDTH + CHARMARGIN) * scale;
		} else if (string[i] == '\n'){
			xCount = x;
			yCount += (FONT_HEIGHT + CHARMARGIN) * scale;
		}
	}
}