import React, { useContext } from 'react';
import { AllPlaylistsContext } from '../../../../contexts/AllPlaylistsContext/AllPlaylistsContext'
import { AllPlaylistsTopBarBox } from './AllPlaylistsTopBar.css';
import IconButton from '../../../../elements/IconButton/IconButton';

const { dialog } = require('electron').remote;

const AllPlaylistTopBar = (): JSX.Element => {
  const { allPlaylists, setAllPlaylists } = useContext(AllPlaylistsContext);

  const handleAddNewPlaylist = async() => {
    const file = await dialog.showOpenDialog(null, {
      title: 'Wybierz plik',
      properties: ['openFile'],
      filters: [{ name: 'r1x/r2x', extensions: ['r1x', 'r2x'] }],
    });
    
    // Dodaj plik playlisty, jeśli użytkownik nie anulował wyboru pliku
    if (file.canceled === false) {
      const newPlaylists = [...allPlaylists];
      newPlaylists.push({
        rowid: allPlaylists.length,
        name: file.filePaths[0].split('\\').pop(),
        description: file.filePaths[0].split('\\').splice(-2)[0],
        input: file.filePaths[0],
        problemFiles: [],
      });
      setAllPlaylists(newPlaylists);
    }
  }

  return (
    <AllPlaylistsTopBarBox>
      <IconButton bgColor="main" icon="plus" onClick={handleAddNewPlaylist} title="Dodaj nową playlistę" />
    </AllPlaylistsTopBarBox>
  )
};

export default AllPlaylistTopBar;