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

	message(data){
		switch(data.type){
			case 'connect':
				this.playerId = data.data.playerId;
				for (let i = 0; i<data.data.players.length; i++) {
					let p = data.data.players[i];
					if(p.id==this.playerId)
						player=new Player(p.id,p.x,p.y,0,p.name,p.dir);
					else
						players.push(new Player(p.id,p.x,p.y,0,p.name,p.dir));
				}
				break;

			case 'update':
				updatePlayer(data.data);
				break;

			case "newplayer":
				players.push(new Player(data.data.id, data.data.x, data.data.y, 0, data.data.name, data.data.dir));
				break;

			case "removePlayer":
				removePlayer(data.data.id);
				break;

			case "newBullet":
				bullets.push(new Bullet(data.data.x,data.data.y,data.data.z==undefined?0:data.data.z,data.data.dx,data.data.dy,data.data.id));
				break;

			case "died":
				console.log("player",data.data.id,"was killed by",data.data.killerId);
				addKill(data.data.id,data.data.killerId);
				break;

			case "message":
				phone.addMessage(data.data);
				break;

			case "kick":
				if(data.data.player_id == player.id){
					alert("Vous avez essayé de tricher, vous jouez maintenant en solo.");
				}else{
					console.log("Player " + data.data.player_id.toString() + " caught cheating.");
				}
				break;

			default:
				console.log("received unknown data:",data);
				break;
		}
	}

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

	died(id, killerId){
		this.socket.send(JSON.stringify({type:"died",data:{id: id, killerId: killerId}}));
	}

	update(obj){ 		//send data to server in order to broadcast
		this.socket.send(JSON.stringify({
			type: "update",
			data: obj
		}));
	}

	newBullet(x,y,z,dx,dy,parentId)
	{
		this.socket.send(JSON.stringify({type:"newBullet",data:{x: x,y: y,z: z,dx: dx,dy: dy,id:parentId}}));
	}

	sendMessage(title, content){
		this.socket.send(JSON.stringify({type: "message", data: {title: title, content: content}}));
	}
}
