import React, {Fragment, useEffect, useState} from 'react';

import {capitalize, toDuration} from "../services/utils";
import {getSong} from "../services/entity_service";

import {Entity} from "../components/Entity";
import {Comments} from "../components/Comments";

const Song = (props) => {
  const song = props.song;

  if(!song) {
    return <Fragment/>
  }

  let subtitle = ''

  if(song.disambiguation && song.length) {
    subtitle = <span>{capitalize(song.disambiguation)} - [{toDuration(song.length)}]</span>
  }else if (song.disambiguation) {
    subtitle = <span>{capitalize(song.disambiguation)}</span>
  }else if (song.length) {
    subtitle = <span>[{toDuration(song.length)}]</span>
  }

  return <Entity title={song.title} subtitle={subtitle}/>

}

export const SongView = (props) => {
  const mbid = props.match.params.mbid;
  const [song, setSong] = useState(null);

  useEffect(() => {
    if (mbid) {
      getSong(mbid).then((result) => setSong(result));
    }
  }, [mbid]);

  return (
    <div>
      <Song song={song}/>
      {song &&
        <Comments/>
      }
    </div>
  )

}
