#include "socket.h"
#include "world.h"
#include "socket.h"
#include "simpleclass.h"
#include <cassert>


struct WorldBase {
	Socket socket;
	WorldBase(const char *ip , int port) : socket(ip, port) {}
};


World::World(const char *ip, int port){
	base = new WorldBase(ip, port);
}


void World::makeMove(){
	lock();
	base->socket.writeInt(CLIENT_BEGIN_MARKER);
	player.write(base->socket);
	base->socket.writeInt(CLIENT_END_MARKER);
	base->socket.flush();

	int marker = base->socket.nextInt();
	if (marker != WORLD_BEGIN_MARKER){
		fprintf(stderr, "Protocol error. Wrong WORLD_BEGIN_MARKER. Expected %d, got %d\n", WORLD_BEGIN_MARKER, marker);
		exit(EXIT_PROTOCOL_ERROR);
	}

	player.read(base->socket);
	for (int i = 0; i < MAXMONSTERS; i++)
		monsters[i].read(base->socket);

	for (int i = 0; i < MAXMISSILES; i++)
		missiles[i].read(base->socket);

	marker = base->socket.nextInt();
	if (marker != WORLD_END_MARKER){
		fprintf(stderr, "Protocol error. Wrong WORLD_END_MARKER. Expected %d, got %d\n", WORLD_END_MARKER, marker);
		exit(EXIT_PROTOCOL_ERROR);
	}

	unlock();
}

void World::run(float _vx, float _vy){
	player.RunX = _vx;
	player.RunY = _vy;
}

void World::shoot(float _shootx, float _shooty){
	player.ShootX = _shootx;
	player.ShootY = _shooty;
}

void World::lock(){
	base->socket.lock();
}

void World::unlock(){
	base->socket.unlock();
}

World::~World(){
	delete base;
}
