#include "globals.h"

#include <SDL_net.h>
#include <string.h>
#include "blpstream.h"
#include "drawprimitives.h"
#include "globals.h"

// global
BLP_Frame currentBLPFrame;
Uint32 currentBLPFrameNum;

// more or less local
UDPsocket BLPsd;
IPaddress BLPsrvadd;
UDPpacket *BLPp;
Uint32 blpLastTick;

void initBLPFrames() {
	// Reset frame number
	currentBLPFrameNum = 0;
	
	
	// Open UDP Port
	//   Get the socket
    if (!(BLPsd = SDLNet_UDP_Open(BLPSTREAM_TARGETPORT))) {
        fprintf(stderr, "SDLNet_UDP_Open: %s\n", SDLNet_GetError());
        exit(EXIT_FAILURE);
    }
	
    //   Resolve server name
    if (SDLNet_ResolveHost(&BLPsrvadd, BLPSTREAM_TARGETHOST, BLPSTREAM_TARGETPORT)) {
        fprintf(stderr, "SDLNet_ResolveHost(%s %d): %s\n", BLPSTREAM_TARGETHOST, BLPSTREAM_TARGETPORT, SDLNet_GetError());
        exit(EXIT_FAILURE);
    }
	
	/* Allocate memory for the packet */
    if (!(BLPp = SDLNet_AllocPacket(sizeof(currentBLPFrame)))) {
        fprintf(stderr, "SDLNet_AllocPacket: %s\n", SDLNet_GetError());
        exit(EXIT_FAILURE);
    }
	
	blpLastTick = SDL_GetTicks() + 10;
	
}

void deInitBLPFrames() {
	SDLNet_FreePacket(BLPp);
	SDLNet_UDP_Close(BLPsd);
}

void recieveBLPFrame(bool matrixMode) {
	while(!SDLNet_UDP_Recv(BLPsd, BLPp)) {

		SDL_Event event;
		while (SDL_PollEvent(&event)) 
		{
			switch (event.type) 
			{
				case SDL_KEYUP:
					exit(0);
					break;
			}
		}
		
		// Give up rest of allocated kernel timeslot to next program
		SDL_Delay(1);
	}

	memcpy(&currentBLPFrame, BLPp->data, sizeof(currentBLPFrame));

	// Lock Surface if needed
	if (SDL_MUSTLOCK(gScreen))
		if (SDL_LockSurface(gScreen) < 0) 
			return;	
	
	for(Uint32 y = 0; y < 8; y++) {
		for(Uint32 x = 0; x < 18; x++) {
			char cval = currentBLPFrame.pixels[x + y * 18];
			Uint32 color = (Uint32)cval;
			if(!matrixMode) {
				color = color + color * 256 + color * 65536;
			} else {
				color = (color & 0xff) * 256;
			}
			drawrect(x * 20, y * 20, 20, 20, color);
		}
	}
	
	if (SDL_MUSTLOCK(gScreen)) 
		SDL_UnlockSurface(gScreen);

	SDL_Flip(gScreen); /* Update whole screen */
}

