class Network{
	constructor(adress){
		this.adress = adress;
		this.connected = false;

		this.playerId = null;
		this.clientPlayer=null;
		this.playersToAdd = [];
		this.playersToRemove = [];
		this.playersToUpdate = [];
	}

	message(data){
		switch(data.type){
			case 'connect':
				this.playerId = data.data.playerId;
				for (var i = data.data.players.length - 1; i >= 0; i--) {
					if(data.data.players[i].id==this.playerId)
						this.clientPlayer=new Player(data.data.players[i].id, data.data.players[i].x, data.data.players[i].y, data.data.players[i].name, data.data.players[i].dir);
					else
						this.playersToAdd.push(new Player(data.data.players[i].id, data.data.players[i].x, data.data.players[i].y, data.data.players[i].name, data.data.players[i].dir))
				}
				break;
			case 'update':
				this.playersToUpdate.push(data.data);
				break;
			case "newplayer":
				this.playersToAdd.push(new Player(data.data.id, data.data.x, data.data.y, data.data.name, data.data.dir));
				break;
			case "removePlayer":
				this.playersToRemove.push(data.data.id);
				break;
		}
	}

	connect(){
		this.socket = new WebSocket(this.adress);
		this.socket.addEventListener('open', (e)=>{
			//connected to server
			this.connected = true;
		});
		this.socket.addEventListener('message', (e)=>{
			this.message(JSON.parse(e.data));
		})
	}

	getPlayerId(){
		while(this.playerId==null){
			//waiting for connection
		};
		return this.playerId;
	}

	update(obj){
		this.socket.send(JSON.stringify({
			type: "update",
			data: obj
		}))
	}

	getPlayersToAdd(){
		let tmp = this.playersToAdd;
		this.playersToAdd = [];
		return tmp;
	}

	getPlayersToRemove(){
		let tmp = this.playersToRemove;
		this.playersToRemove = [];
		return tmp;
	}

	getPlayersToUpdate(){
		let tmp = this.playersToUpdate;
		this.playersToUpdate = [];
		return tmp;
	}
}