import * as _ from "lodash";
import { TrackInfo, getTracks, playTrack, stopPlayback } from "./client";
import { DataCard } from "./components/DataCard";
import { NowPlaying } from "./components/NowPlaying";
import { TextField } from "./components/TextField";
import { TrackCard } from "./components/TrackCard";
import { PlaylistRow } from "./components/PlaylistRow";

window.customElements.define("data-card", DataCard);
window.customElements.define("now-playing", NowPlaying);
window.customElements.define("text-field", TextField);
window.customElements.define("track-card", TrackCard);
window.customElements.define("playlist-row", PlaylistRow);

declare global {
  interface HTMLElementTagNameMap {
    "data-card": DataCard;
    "now-playing": NowPlaying;
    "text-field": TextField;
    "track-card": TrackCard;
    "playlist-row": PlaylistRow;
  }
}

const updateTrackList = (tracks: TrackInfo[]) => {
  const playlist = document.querySelector(".track-list__tracks");
  if (playlist) {
    _.map(tracks, (info) => {
      let card: TrackCard = document.createElement("track-card");
      let listItem: PlaylistRow = document.createElement("playlist-row");

      card.trackId = info.id;
      card.name = info.name || null;
      card.album = info.album || null;
      card.artist = info.artist || null;
      card.duration = (info.duration && `${info.duration}`) || null;

      listItem.appendChild(card);
      listItem.trackId = info.id;
      listItem.onPlay = (id: string) => {
        playTrack(id);
      };
      playlist.appendChild(listItem);
    });
  } else {
    console.log("track_list does not exist");
  }
};

const updateNowPlaying = (track: TrackInfo) => {
  const track_list = document.querySelector("#now-playing");
  if (track_list) {
    let card: NowPlaying = document.createElement("now-playing");
    card.name = track.name || null;
    card.album = track.album || null;
    card.artist = track.artist || null;
    track_list.appendChild(card);
    card.onStop = () => stopPlayback();
  }
};

const run = () => {
  updateNowPlaying({
    id: "example id",
    name: "Underground",
    album: "Artemis",
    artist: "Lindsey Stirling",
  });
  getTracks().then((tracks) => updateTrackList(tracks));
};

run();
