class Car {
  constructor(lng, lat) {
    this.lng = lng;
    this.lat = lat;

    this.speed = 0;
    this.direction = 0;
    this.maxSpeed = 0.0025;
    this.accel = 0.00008;
    this.friction = 0.96;

    this.img = new Image();
    this.img.src = "assets/car.png";
  }

  update() {
    if (keys.up) this.speed += this.accel;
    if (keys.down) this.speed -= this.accel * 0.7;

    this.speed *= this.friction;

    if (keys.left) this.direction -= 2;
    if (keys.right) this.direction += 2;

    if (this.speed > this.maxSpeed) this.speed = this.maxSpeed;
    if (this.speed < -this.maxSpeed * 0.5) this.speed = -this.maxSpeed * 0.5;

    const rad = this.direction * Math.PI / 180;
    this.lng += Math.sin(rad) * this.speed;
    this.lat += Math.cos(rad) * this.speed * -1;
  }

  draw(ctx, map) {
    const pos = map.project([this.lng, this.lat]);
    const size = 40;

    ctx.save();
    ctx.translate(pos.x, pos.y);
    ctx.rotate((-this.direction + 180) * Math.PI / 180);
    ctx.drawImage(this.img, -size/2, -size/2, size, size);
    ctx.restore();
  }
}