const imgPlayer = new Image();
const imgBullet = new Image();
const imgCar = new Image();
const map = new Image();
const map_night = new Image();
const map2 = new Image();
imgPlayer.src = "./assets/body.png";
imgBullet.src = "./assets/bullet.png";
imgCar.src = "./assets/car.png";
map.src = "./assets/map/map_principale.png"
map_night.src = "./assets/map/map_principale_nuit.png"
map2.src = "./assets/map/map_secondaire.png";

class Render {
	constructor(idCanvas) {
		let canvas = document.getElementById(idCanvas);
		this.ctx = canvas.getContext("2d");
		this.ctx.imageSmoothingEnabled=false;
		//this.ReloadAff();
	}

	RenderPlayer(player,client) {
		if(player==null)
			return;
		let x=player.x
		let y=player.y
		if(x>=2000 && y>=2000 && this.map==1) {
			x=player.x-2000
			y=player.y-2000
		}

		//this.map==1 && (x<2000 || y<2000)
		if((this.map==1 && player.x>=2000 && player.y>=2000) || (this.map==0 && x<2000 && y <2000)) {
			this.ctx.save();
		    this.ctx.translate(x, y);
		    this.ctx.rotate(player.angle);
		    this.ctx.drawImage(imgPlayer, -playerSize / 2, -playerSize / 2, playerSize, playerSize);
		    this.ctx.restore();
			this.ctx.fillStyle = 'white';
	        this.ctx.font="10pt arial";
	        this.ctx.fillText(player.name,x-player.name.length*10/3,y-playerSize/1.8);
	        if(client) {
				this.ctx.fillStyle = 'red';
			    this.ctx.fillRect(x-playerSize/2-5, y-playerSize/2, playerSize+10, 5);
				this.ctx.fillStyle = '#7AFF33';
			    this.ctx.fillRect(x-playerSize/2-5, y-playerSize/2, player.health*(playerSize+10)/defaulthealth, 5);
	        }
		}
	}

	RenderCar(x,y,angle) {
		if(this.map==0) {
		    this.ctx.save();
		    this.ctx.translate(x, y);
		    this.ctx.rotate(angle);
		    this.ctx.drawImage(imgCar, -carSize*1513/750 / 2, -carSize / 2, carSize*1513/750, carSize);
		    this.ctx.restore();
		}
	}

	RenderBullet(x,y) {
		/*
		if(this.map==1) {
			x = x-2000;
			y = y-2000;
		}*/
	    this.ctx.save();
	    this.ctx.translate(x, y);
	    this.ctx.drawImage(imgBullet, -20 / 2, -20 / 2, 20, 20);
	    this.ctx.restore();
	}

	ReloadAff() {
		
		//const fond = new Image();
		if(player!=null && player.x >= 2000 && player.y >=2000) {
			this.map=1;
		} else {
			this.map=0;
		}

		let fond;
		let date = new Date();

		if(date.getHours()<=18){
			fond = map;
		}else{
			fond = map_night;
		}
		/*
		if(this.map==0) {
			let fond = map;
		} else {
			let fond = map2;
		}
		*/
		let mapWidth = fond.width;
		let mapHeight = fond.height;
		this.ctx.canvas.width = mapWidth;
		this.ctx.canvas.height = mapHeight;
	    this.ctx.drawImage(fond, 0, 0, mapWidth, mapHeight);
		this.RenderPlayer(player,true);
        cars.forEach((car) => {
            this.RenderCar(car.x,car.y,car.angle+(car.drift>0?2.1:0));
        });
   		players.forEach((player) => {
   			this.RenderPlayer(player,false);
   		})
		bullets.forEach((bullet) => {
			this.RenderBullet(bullet.x,bullet.y);
		});
	}
}