import React, { useState, useContext } from 'react';
import SectionHeader from '../../elements/SectionHeader/SectionHeader';
import { AllPlaylistsContext, AllPlaylistInterface } from '../../contexts/AllPlaylistsContext/AllPlaylistsContext'
import { ConfigContext } from '../../contexts/ConfigContext/ConfigContext';
import { PlaylistContext } from '../../contexts/PlaylistContext/PlaylistContext';
import { PlaylistContext2 } from '../../contexts/PlaylistContext2/PlaylistContext2';
import AllPlaylistsTopBar from './components/AllPlaylistsTopBar/AllPlaylistsTopBar'
import { AllPlaylistsBox, AllPlaylistsItemsBox, SinglePlaylistItem, SinglePlaylistItemButtons, FolderText } from './AllPlaylists.css';
import { retreivePlaylistFile, selectSingleFiles } from './functions';
import IconButton from '../../elements/IconButton/IconButton';
import { useAlert } from 'react-alert';
import 'react-confirm-alert/src/react-confirm-alert.css'

const AllPlaylists = (
    props: {
      playlistRef: { current: { resetPlaylistSettings: () => void, autostart: () => void, stopAll: (stopVideo: boolean) => void, play: () => void }},
      playlist2Ref: { current: { resetPlaylistSettings: () => void, autostart: () => void, stopAll: (stopVideo: boolean) => void, play: () => void }},
    }
): JSX.Element => {
  const [activePlaylist, setActivePlaylist] = useState(-1);
  const { allPlaylists, setAllPlaylists } = useContext(AllPlaylistsContext);
  const { config } = useContext(ConfigContext);
  const { setPlaylist } = useContext(PlaylistContext);
  const { setPlaylist: setPlaylist2 } = useContext(PlaylistContext2);

  const alert = useAlert();

  const handlePlaylistDelete = (rowid: number) => {
    const chooseIndex = allPlaylists.findIndex( (x: {rowid: number}) => x.rowid === rowid );
    const newAllPlaylist = [...allPlaylists];
    newAllPlaylist.splice(chooseIndex, 1);
    setAllPlaylists(newAllPlaylist);
  }

  const handleTestPlaylistFiles = async (rowid: number) => {
    const testPlaylist = allPlaylists.find( (x: {rowid: number}) => x.rowid === rowid );
    const playlistData = await retreivePlaylistFile(testPlaylist.input, config);
    const singleFiles = selectSingleFiles(playlistData);

    const problemFiles: string[] = [];
    for(const file of singleFiles) {
      const fileCorrect = await checkSingleFiles(file);
      if (!fileCorrect) {
        problemFiles.push(file);
      }
    }

    const testPlaylistIndex = allPlaylists.findIndex( (x: {rowid: number}) => x.rowid === rowid );
    const newAllPlaylists = [...allPlaylists];
    testPlaylist.problemFiles = problemFiles;
    newAllPlaylists[testPlaylistIndex] = testPlaylist;
    setAllPlaylists(newAllPlaylists);
    window.gridPlayers[config.rows - 1][config.columns - 1].stop();
    if (problemFiles.length === 0) {
      alert.success('Wszystkie pliki przeszły test');
    } else {
      alert.error('Błąd');
    }
  }

  const checkSingleFiles = (filePath: string) => {
    return new Promise((resolve) => {
      const row = config.rows - 1;
      const col = config.columns - 1;
      const correctFilepath = filePath.indexOf('|') > -1 ? filePath.split('|')[0] : filePath;
      window.frameReady[row][col] = false;
      window.gridPlayers[row][col].play(`file:\/\/\/${correctFilepath}`);
      setTimeout(() => {
        if (window.frameReady[row][col]) {
          resolve(true);
        } else {
          resolve(false);
        }
      }, 500)
    });
  }

  const handlePlayPlaylistItem = async(rowid: number, playlistWindow: number) => {
    const choosedPlaylist = allPlaylists.find( (x: {rowid: number}) => x.rowid === rowid );
    const chooseIndex = allPlaylists.findIndex( (x: {rowid: number}) => x.rowid === rowid );
    const playlistData = await retreivePlaylistFile(choosedPlaylist.input, config);

    let found = false;
    for( const p of playlistData ) {
      for( const g of p.grid ) {
        if(!g) continue;
        if (g.fileError) {
          alert.error('Brak pliku(ów)');
          found = true;
          break;
        }
      }
      if (found) break;
    }

    if (playlistWindow === 1) {
      props.playlistRef.current.stopAll(false);
      setPlaylist(playlistData);
    } else {
      props.playlist2Ref.current.stopAll(false);
      setPlaylist2(playlistData);
    }
    setActivePlaylist(chooseIndex);
  };

  // const handleStartBothPlaylists = () => {
  //   props.playlistRef.current.play();
  //   props.playlist2Ref.current.play();
  // }

  return (
    <AllPlaylistsBox>
      <div style={{display:'flex', justifyContent: 'space-between'}}>
        <SectionHeader title="Playlisty" />
        <AllPlaylistsTopBar />
      </div>
      {allPlaylists.length > 0 &&
        <AllPlaylistsItemsBox>
          {
              (allPlaylists as any[]).map(
                (_playlist: AllPlaylistInterface, index: number) => 
                  <SinglePlaylistItem key={index} active={activePlaylist === index}>
                    <div style={{padding: 7}}>
                      {index+1}. {_playlist.name}
                      <FolderText active={activePlaylist === index}><i className="fa fa-folder" style={{marginRight:2}} /> {_playlist.description}</FolderText>
                    </div>
                    <SinglePlaylistItemButtons className="button-box">
                      <IconButton bgColor="red" padding={10} icon="trash" onClick={() => handlePlaylistDelete(_playlist.rowid)} title="Skasuj playlistę" customStyle={{marginRight: 5}} />
                      <IconButton bgColor="main" padding={10} icon="tv" onClick={() => handleTestPlaylistFiles(_playlist.rowid)} title="Testuj playlistę" customStyle={{marginRight: 5}} />
                      <IconButton bgColor="second" padding={7} icon="chevron-right" hideIcon={true} displayText={true} onClick={() => handlePlayPlaylistItem(_playlist.rowid, 1)} title="1" customStyle={{marginRight: 5, width:30}} />
                      <IconButton bgColor="second" padding={7} icon="chevron-right" hideIcon={true} displayText={true} onClick={() => handlePlayPlaylistItem(_playlist.rowid, 2)} title="2" customStyle={{marginRight: 5, width:30}} />
                      {/* <IconButton bgColor="second" padding={10} icon="bolt" onClick={() => handlePlayPlaylistItem(_playlist.rowid, true)} title="Włącz playlistę i wystartuj" /> */}
                    </SinglePlaylistItemButtons>
                    {_playlist.problemFiles.length > 0 &&
                      <div style={{color: 'red', padding: 10, border: '1px solid red', textAlign: 'center', background: '#fff', borderRadius: 4}}>
                        <div><i className="fa fa-exclamation-circle" /> problematyczne pliki</div>
                        <div>
                          {_playlist.problemFiles.map((prFile) => {
                            return (
                              <div key={prFile}>{prFile.split('\\').pop()}</div>
                            )
                          })}
                        </div>
                      </div>
                    }
                  </SinglePlaylistItem>
              )
          }
        </AllPlaylistsItemsBox>
      }
    </AllPlaylistsBox>
  )
};

export default AllPlaylists;