import { PLAT_TYPE } from './constants.js';
import { cameraInput } from './cameraControl.js';


export function createPlayer() {
  const player = new Sprite();
  player.scale = 0.20;
  player.img = "assets/nubzuki.png";
  player.bounciness = 0;
  player.rotationLock = true;

  player.w = 20;
  player.h = 20;
  player.offset.y = 25;
  player.elevation = 0;
  player.x = width / 2;
  player.y = height - 80;
  return player;
}


function handleJump(player, platform) {

  let elevationGain = 0;
  if (player.elevation < platform.elevation) {
    elevationGain = platform.elevation - player.elevation;
    player.elevation = platform.elevation;
  }

  switch (platform.type) {
    case PLAT_TYPE.ONE_TIME:
      player.vel.y = -7.5;
      platform.remove();
      break;
    case PLAT_TYPE.SPRING:
      player.vel.y = -13;
      break;
    default:
      player.vel.y = -7.5;
  }

  return elevationGain;
}

export function updatePlayerPosition(player, platforms) {

  // Controls
  player.vel.x = 0;
  if (keyIsDown(LEFT_ARROW) || cameraInput.left) {
    player.vel.x = -5;
  } else if (keyIsDown(RIGHT_ARROW) || cameraInput.right) {
    player.vel.x = 5;
  } else {
    player.vel.x *= 0.5;
  }


  // Wrap horizontally
  if (player.x > width) {
    player.x = 0;
  } else if (player.x < 0) {
    player.x = width;
  }

  // Jumping thrue platforms
  for (let plat of platforms) {
    if (player.vel.y <= 0 && player.y + player.offset.y > plat.y) {
      plat.collider = 'none';
    } else {
      plat.collider = 'static';
    }
  }

  // Automatic jumping
  if (player.vel.y >= 0) {
    for (let i = 0; i < platforms.length; i++) {

      if (player.colliding(platforms[i])) {
        return handleJump(player, platforms[i]);
      }
    }
  }

  return 0;
}
