import RecordPlayer from "./RecordPlayer.js";

export default class TapeDeck {
  //--------------------------
  // constructor
  //--------------------------
  constructor() {
    let self = this;
    this.rp = new RecordPlayer();
    this.tapeSelect = document.querySelector(".tape-select");
    this.tapeTracklist = document.querySelector(".tape-tracklist");
    this.tapeCover = document.getElementById("tape-cover");
    this.tapeTitle = document.getElementById("tape-title");
    this.tapeControls = document.getElementById("tape-controls");
    this.logo = document.querySelector(".the-logo");
    this.logo.addEventListener("click", (e) => {
      self.tapeSelect.classList.remove("back-left");
      self.tapeSelect.classList.add("front");
      self.tapeTracklist.classList.remove("front");
      self.tapeTracklist.classList.add("back-right");
      self.tapeControls.classList.add("control-closed");
      self.tapeControls.classList.remove("control-open");
    });

    var request = new XMLHttpRequest();
    request.open("GET", "api/tapes/list", true);
    request.onload = () => {
      if (request.status == 200) {
        let response = JSON.parse(request["response"]);
        //console.log(response);
      } else {
        let error = JSON.parse(request["response"]);
        consolel.log();
      }
    };
    request.send();
    //make images buttons for playlist retrieval
    var covers = document.querySelectorAll(".covers");
    for (var i = 0, length = covers.length; i < length; i++) {
      covers[i].addEventListener("click", (e) => this.handleCovers(e), false);
    }
  }

  //event handlers

  handleCovers(e) {
    e.stopPropagation();
    e.preventDefault();

    var request = new XMLHttpRequest();
    let self = this;
    request.open("GET", "api/tapes/tracklist/" + e.target.id, true);
    request.onload = () => {
      if (request.status == 200) {
        let response = JSON.parse(request["response"]);
        //once playlist is loaded, flip to list mode
        self.tapeSelect.classList.remove("front");
        self.tapeSelect.classList.add("back-left");
        self.tapeTracklist.classList.remove("back-right");
        self.tapeTracklist.classList.add("front");
        self.tapeCover.src = e.target.src;
        self.tapeTitle.innerText = "VOL. " + response[0].tape;
        //open tape controls
        self.tapeControls.classList.remove("control-closed");
        self.tapeControls.classList.add("control-open");
        //set up player
        self.rp.setTrackList(response);
      } else {
        let error = JSON.parse(request["response"]);
      }
    };
    request.send();
  }
}
