#include "OutputHelpers.h"

/*****      Output Functions     *****/
//These funcions help to print the truck data to the screen
//This finally works as an Output method
//Max number of rects is 399 therefore a maximum of 399 bits can be drawn at a time
//The truck list entrys have to be printed as one per frame

float pixelWidth = 0.001;
float lineWidth;
float charWidth;
float pixelHeight;
float lineHeight;

void setupPixelSize() {
	int width;
	int height;
	GRAPHICS::_GET_SCREEN_ACTIVE_RESOLUTION(&width, &height);
	std::cout << "screen:" << width << "|" << height << std::endl;
	pixelWidth = 1.0F / width;
	pixelHeight = 1.0F / height;
	lineWidth = pixelWidth * 1;
	charWidth = pixelWidth * 8;
	lineHeight = pixelHeight * 12;

	std::cout << "PixelWidth:" << pixelWidth << std::endl;
	std::cout << "LineWidth:" << lineWidth << std::endl;
	std::cout << "CharWidth:" << charWidth << std::endl;
}


//White line (white pixel) is 1, black is 0
void drawCharAsLines(char character, float pixelOffset) {
	for (int i = 0; i < 8; i++) {
		float xCenterPos = (lineWidth * float(i)) + pixelOffset + pixelWidth;
		if (((character << i) & 0b10000000) == 0b10000000) {
			GRAPHICS::DRAW_RECT(xCenterPos, 0, lineWidth, 0.05, 256, 256, 256, 256);
		}
		else {
			GRAPHICS::DRAW_RECT(xCenterPos, 0, lineWidth, 0.05, 0, 0, 0, 256);
		}
	}
}

//Decode function
//Pseudo Code for implementation in other screen reader program
/*
Hint: A truck list entry has 21 chars aka. 168 Bits -> 168 pixels
 Steps for decoding:
 1. get chars from lines (21 chars in total)
 2. put them together into a string
 3. split string on ',' character to get the seperate fields
 4. put the fields into a truck object
*/
char getCharacterFromLines(float pixelOffset) {
	const int WHITE = 1; //depends on the color value for white
	char output = 0b00000000;
	for (int i = 0; i < 8; i++) {
		
		int x = pixelOffset + 1;
		int y = 1;

		// Python code snippets
		/*
			import ImageGrab

			px = ImageGrab.grab(bbox =(0, 0, 168, 4)).load()

			color = px[x, y]
			isWhite = (color[0] == 255) #Full red, -> part of white color
		*/

		int pixelColor;// = getPixel(x, y).color();
		
		bool nextBit = (pixelColor == WHITE); //the color check might not be that simple
		//nextBit can be 0b00000001 or 0b00000000

		output = output | (nextBit << (7 - i));//insert the next bit into the output
	}
	return output;
}

void testScreenDrawing() {
	drawCharAsLines('H', 0);
	drawCharAsLines('E', charWidth * 1);
	drawCharAsLines('L', charWidth * 2);
	drawCharAsLines('L', charWidth * 3);
	drawCharAsLines('O', charWidth * 4);
}

void encodeString(std::string input) {
	for (int i = 0; i < input.size(); i++) {
		drawCharAsLines(input.at(i), charWidth * i);
	}
}

void drawStartSignal() {
	TruckListEntry nullTruck;
	nullTruck.id = 0;
	nullTruck.distanceToPlayer = 0;
	nullTruck.angleToPlayer = 0;
	nullTruck.heading = 0;
	nullTruck.velocity = 0;
	encodeString(listEntryToCsv(nullTruck));
}