import React, {Fragment, useEffect, useState} from 'react';
import {Link} from "react-router-dom";

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

import {CoverArt} from "../components/CoverArt";
import {Entity} from "../components/Entity";
import {EntityList} from "../components/EntityList";


const Recordings = (props) => {
  const recordings = props.recordings ? props.recordings : null;

  let recordingsComponent = <EntityList placeholder={true} size={25}/>;
  if(recordings) {
    const items = recordings.map((recording) => ({
      'id': recording.id,
      'link': props.makeLink(recording.id),
      'title': recording.title,
      'subtitle': (<Fragment>
                    {recording.length && <div>[{toDuration(recording.length)}]</div>}
                    {recording.disambiguation && <div>{capitalize(recording.disambiguation)}</div>}
                  </Fragment>),
      'selected': props.selected === recording.id

    }));
    recordingsComponent = <EntityList items={items}/>
  }

  return (
    <Fragment>
      <h2>Canciones</h2>
      {recordingsComponent}
    </Fragment>
  )
}

const Release = (props) => {
  const release = props.release;
  if (release){
    const subtitle = (
      <Link to={`/artist/${release.artist.id}`}>
        {`${release.artist.name} (${release.date})`}
      </Link>
    )
    return <Entity title={release.title}
      subtitle={subtitle}
      buttonText='Agregar a mi lista'
      cover={<CoverArt release={release}/>}/>
  }else {
    return <Fragment></Fragment>
  }
}

export const ReleaseView = (props) => {
  const mbid = props.match.params.mbid;

  const [release, setRelease] = useState(null);
  const [recordings, setRecordings] = useState(null);
  const currentRecording = props.location.hash ? props.location.hash.slice(1) : null

  useEffect(() => {
    if (mbid) {
      getRelease(mbid).then((result) => setRelease(result));
      getReleaseSongs(mbid).then((result) => {
        setRecordings(result.medias[0].recordings);
      });
    }
  }, [mbid])

  const makeLink = (recordingID) => {
    return `/release/${mbid}#${recordingID}`;
  }

  const handleNavigateToRecording= (recording) => {
    props.history.push(makeLink(recording.id))
  }

  return (
    <Fragment>
      <Release release={release}/>
      {release &&
        <Recordings recordings={recordings}
                    selected={currentRecording}
                    makeLink={makeLink}
                    navigateToRecording={handleNavigateToRecording}/>
      }
    </Fragment>
  )
}
