import state from './state.js';
import chartmgr from './chartmgr.js';
import { KeyHint } from './ui.js'
import { sndBoop, sndSongselect } from './main.js';

export class SongSelectScreen {
  constructor() {
    this.covers = [...chartmgr.covers.entries()].map(c => c[1])
    this.songs = [...chartmgr.cache.entries()].map(c => c[1])
    this.curSelection = 0;
  }
  
  draw() {
    KeyHint.draw(">", width - 48 - 4, (height / 2) + 100)
    KeyHint.draw("<", 48 - 8, (height / 2) + 100)
    KeyHint.draw("Enter", (width/2) - 24, height - 40)

    textSize(36);
    fill(255);
    text("Select a song", 16, 48);

    fill(215);
    stroke(0);

    // current song
    image(this.covers[this.curSelection], (width-256)/2, (height-256)/2, 256, 256)

    textSize(48);
    text(this.songs[this.curSelection].name, 
      (width / 2) - (textWidth(this.songs[this.curSelection].name) / 2), 
    height - 128 - 36);

    textSize(24);
    text(this.songs[this.curSelection].artist, 
      (width / 2) - (textWidth(this.songs[this.curSelection].artist) / 2), 
    height - 128);

    let etcmeta = this.songs[this.curSelection].difficulty + " - " + this.songs[this.curSelection].len

    textSize(18);
    text(etcmeta, 
      (width - textWidth(etcmeta) ) / 2, 
    height - 128 + 32);

    let nextSelection = (this.curSelection + 1 > this.songs.length - 1)
      ? 0
      : this.curSelection + 1

    let prevSelection = (this.curSelection - 1 < 0)
      ? this.songs.length - 1
      : this.curSelection - 1

    image(this.covers[prevSelection], 
      32, (height - 128) / 2, 128, 128);

    image(this.covers[nextSelection], 
      (width - 128) - 32, (height - 128) / 2, 128, 128);
  }

  async keyPressed() {
    switch(keyCode) {
      case 37:
        if(this.curSelection - 1 < 0) {
          this.curSelection = this.songs.length - 1
        } else {
          this.curSelection -= 1
        }
        sndBoop.play()
        break;

      case 39: //right
        if(this.curSelection + 1 > this.songs.length - 1) {
          this.curSelection = 0
        } else {
          this.curSelection += 1
        }
        sndBoop.play()
        break;

      case 13: //enter
        sndSongselect.play();
        window.gameScreen = await chartmgr.loadChart(this.songs[this.curSelection].id)
        state.setState("game");
        redraw()
        break;
    }
  }
}