import React, { useState, useEffect } from "react";
import Library from "./Library";
import { connect } from "react-redux";

import "../styles/player.css";
import { setCurrentTrack } from "../actions/playerActions";

// this.props.playlist
const Player = ({ playlist, currentTrack, setCurrentTrack }) => {
  const [isAutoplayed, setIsAutoplayed] = useState(true);

  function goPrevTrack() {
    setIsAutoplayed(true);
    currentTrack > 0 && setCurrentTrack(currentTrack - 1);
  }
  function goNextTrack() {
    setIsAutoplayed(true);
    currentTrack < playlist.length && setCurrentTrack(currentTrack + 1);
  }

  return (
    <div className="player">
      <button className="prevTrack" onClick={goPrevTrack}></button>
      {!!playlist.length && (
        <audio
          controls
          src={playlist[currentTrack] && playlist[currentTrack].url}
          autoPlay={isAutoplayed}
        />
      )}
      <button className="nextTrack" onClick={goNextTrack}></button>
    </div>
  );
};

const mapStateToProps = (state) => ({
  currentTrack: state.player.currentTrack,
});

const mapDispatchToProps = (dispatch) => ({
  setCurrentTrack: (trackIndex) => dispatch(setCurrentTrack(trackIndex)),
});

export default connect(mapStateToProps, mapDispatchToProps)(Player);
