import {
  Entity,
  Sprite
} from './entity.js';
import { GameScreen } from './screenGame.js';
import { SongSelectScreen } from './screenSongSelect.js';
import {
  KeyHint
} from './ui.js'
import chartmgr from './chartmgr.js';
import state from './state.js';

const charts = [
  "bozo",
  "dashstar",
  "golddust",
  "pixelpalace"
  // "test"
]

// STUFF
let songSelectScreen;

// ASSETS
let sndBoop;
let sndCombobreak;
let sndSongselect;
let fntRenogare;

function blur(col, blurFactor) {
  drawingContext.shadowColor = col;
  drawingContext.shadowBlur = blurFactor;
}

function debugMsg(msg) {
  fill(255);
  stroke(0);
  textSize(12);
  text(msg, 24, 24);
}

function drawFps() {
  let fps = frameRate();
  fill(255);
  stroke(0);
  textSize(12);
  text("FPS: " + fps.toFixed(2), 10, height - 10);
}

async function preload() {
  console.log("preloading..")

  // load sounds
  soundFormats('mp3')
  sndCombobreak = loadSound('./assets/sfx/combobreak');
  sndCombobreak.volume = 0.6

  sndBoop = loadSound('./assets/sfx/boop')
  sndBoop.volume = 0.6

  sndSongselect = loadSound('./assets/sfx/songselect')
  sndSongselect.volume = 0.4

  // load fonts
  fntRenogare = loadFont("./assets/fonts/Renogare-Regular.otf");
}

async function setup() {
  console.log("setting up..")
  // frameRate(144)
  frameRate(60)
  createCanvas(1280, 720)

  for await (let chartid of charts) {
    try {
      await chartmgr.get(chartid)
    } catch(e) {
      console.log(`error loading chart ${chartid}`, e)
    }
  }

  songSelectScreen = new SongSelectScreen();
  // gameScreen = await chartmgr.loadChart('test')
}

function draw() {
  textFont(fntRenogare);
  background(10)

  switch(state.state) {
    case "game":
      if(!window.gameScreen) {
        debugMsg("err: gamescreen not initialized!")
        break;
      }

      if(!window.gameScreen.song.isLoaded()) {
        fill(255);
        stroke(0);
        textSize(12);
        text("Loading song..", (width - textWidth("Loading song..")) / 2, height /2);

        fill(40, 40, 255)
        rect(0,0,window.gameScreen.loadPercent * width, 12)

        break;
      }
        
      window.gameScreen.calcBeat();
      window.gameScreen.draw();
      break;

    case "songselect":
      if(!songSelectScreen) {
        debugMsg(`loading charts (${chartmgr.cache.size}/${charts.length})`)
        break;
      }
      songSelectScreen.draw()
      break;
  }

  drawFps();
}

function keyPressed() {
  switch(state.state) {
    case "game":
      window.gameScreen.checkHit();
      break;

    case "songselect":
      songSelectScreen.keyPressed()
      break;
  }
}

// make p5 work in a js module environment because variables
// arent exposed to window by default in module 
window.preload = preload;
window.setup = setup;
window.draw = draw;
window.keyPressed = keyPressed;

export {
  sndCombobreak,
  sndBoop,
  sndSongselect,
  fntRenogare
}