import chartmgr from "./chartmgr.js"
import { Sprite } from './entity.js';
import highscore from "./highscore.js";
import state from "./state.js";
import { KeyHint } from "./ui.js";
import { sndBoop } from "./main.js";

class HighscoreSong extends Sprite {
  static draw(img, name, artist, x, y) {
    fill(255);
    noStroke();

    let wth = 0;
    textSize(18);
    let artistTextWidth = textWidth(artist);
    textSize(24);
    let songTextWidth = textWidth(artist);

    wth += Math.max(artistTextWidth, songTextWidth)
    wth += 128
    
    fill(50)
    rect(x - (wth / 2) - 16, y - 16, wth + 32, 64 + 32, 8)

    fill(255)
    textSize(18);
    text(artist, x + 64 + 16 - (wth / 2), y + 56)
    
    textSize(24);
    text(name, x + 64 + 16 - (wth / 2), y + 32)

    image(img, x - (wth / 2), y, 64, 64);
  }
}

export class HighscoreInputScreen {
  constructor(...args) {
    this._init(...args);

    this.name = "";
  }

  async _init(songId, score) {
    this.song = await chartmgr.get(songId);
    this.cover = chartmgr.covers.get(songId);
    this.score = score;
  }

  draw() {
    if(!this.song)
      return;

    let bigTitle = "NEW HIGHSCORE!";
    fill(255);
    textSize(64);
    let bigTitleW = (width - textWidth(bigTitle));
    text(bigTitle, bigTitleW / 2, 128);

    HighscoreSong.draw(this.cover, this.song.name, this.song.artist, 
      width / 2, 
      (height / 2) - 128
    )

    fill(255);
    textSize(48);
    text(this.score, (bigTitleW / 2) + 128 + 32, 256 + 128 + 32 + 4);

    fill(255);
    textSize(24);
    text("NAME:", bigTitleW / 2, 256 + 128);
    
    for(let i = 0; i < 3; i++) {
      fill(255);
      if(i == this.name.length && (frameCount % 32) > 16) {
        console.log(i)
        fill(255,255,255,0)
      }
      text((this.name.length > i) ? this.name[i] : "_", (bigTitleW / 2) + (i*20), 256 + 128 + 36);
    }

    if(this.name.length > 2) 
      KeyHint.draw("Enter", (bigTitleW / 2) + 8 + 64, 256 + 128 + 36 - 4)
  }

  keyPressed() {
    switch(keyCode) {
      case 8: // backspace
        this.name = this.name.slice(0, this.name.length - 1)
        return;

      case 13: //enter
        if(this.name.length > 2) {
          sndBoop.play();
          highscore.setHighscore(this.song.id, this.name, this.score)
          state.setState("songselect")
        }
        return;
    }

    if(this.name.length > 2)
      return

    // special characters are > 1 letter (eg. SHIFT)
    if(key.length > 1)
      return;

    // regex to check if letter
    if(!key.match(/[a-z]/i))
      return

    sndBoop.play();
    this.name += key.toUpperCase();
  }
}