import { useEffect, useState } from 'react'
import './App.css'
import { Button, ListGroup } from 'react-bootstrap';
import { initials, finales } from './data';
import { BtnColor, Status, Tone } from './types';
import { strings } from './strings';
import { useStateContext } from './store';
import { Params } from './params';
import { ActionType, ToggleType } from './reducer';
import { ButtonSet } from './buttons';
import { getAudio } from './utils';

function App() {

  const { state, dispatch } = useStateContext();

  const [ plaingNo, setPlaingNo ] = useState(0)
  const [ status, setStatus ] = useState(Status.params)
  const [ playlist, setPlaylist ] = useState( [] as HTMLAudioElement[] )

  useEffect( () => {
    if (status===Status.params) {
     console.log('effect for params')
     dispatch({ type: ActionType.refresh })
    }
    if (status===Status.prepare) {
      console.log('effect for preparing')
      preparePlayList(state.randomTones!)
    }
    if (status===Status.playing) {
      console.log('effect for playing')
      playPlayList()
    }
// eslint-disable-next-line react-hooks/exhaustive-deps
    }, [status])

  useEffect( () => {
    console.log(`effect for playList ${playlist.length}`)
    if (playlist.length > 0) setStatus(Status.playing)
  } , [playlist[0]] )

const preparePlayList = (tones: Tone[]) => {
  console.log('tones for playing')
  tones!.forEach(element => console.log(element))
  if ( tones!.length == 0 ) return
  const audios = tones!.map(element => getAudio(element.tone) )
  console.debug(audios)
  if ( audios.length == 0 ) return
  for(let x=0; x<audios.length-1;x++)
  {
    audios[x].onended = () =>  setTimeout( () => {
      const pno = x+2
      setPlaingNo(pno)
      audios[x+1].play()
    }, 1000*state.sylPause! ) ;
  }
  audios[audios.length-1].onended = () => setStatus(Status.plaied)
  setPlaylist(audios)
}

const playPlayList = () => {
  if (playlist.length===0) return;
  setStatus(Status.playing)
  setPlaingNo(1)
  playlist[0].play()
}

const playTone = (index: string) => {
  getAudio(index).play()
}

const renderPlayList = () => {

  return state.randomTones!.map(
      (ton, i) => { return <span key={i}
                            className={`syllable tone${ton.num}`}
                            onClick = {()=>playTone(ton.tone)}
                            >
                            {i+1}{'. '}{ton.caption}{'  '}
                            </span> }
    )
}

  return (
      <>
      <h1>{strings.mainHeader}</h1>
      <ListGroup>

      <ListGroup.Item disabled={status != Status.params}>
        <h2>{strings.selectInitiales}</h2>
        <ButtonSet source={initials} color={BtnColor.blue} toggle={ToggleType.init}/>
      </ListGroup.Item>

      <ListGroup.Item disabled={status != Status.params}>
        <h2>{strings.selectFinales}</h2>
        <ButtonSet source={finales} color={BtnColor.green} toggle={ToggleType.fin}/>
      </ListGroup.Item>

      <ListGroup.Item disabled={status != Status.params}>
        <h2>{strings.params}</h2>
          <Params/>
       </ListGroup.Item>

      <ListGroup.Item>
        { status == Status.params &&
          <>
        Выбрано {state.initiales!.length} инициалей,  {state.finales!.length}  финалей, найдено {state.foundSyllables!.length} слогов, { state.foundTones!.length } тонов , 
        <br/>
        <Button
          variant={state.isFound!() ? "success" : "secondary"}
          size="lg"
          onClick={()=>setStatus(Status.prepare)}
          disabled={!state.isFound!()}>
            {state.isFound!() ?  strings.beginDictation : strings.selectInitAndFin }
          </Button>
          </>
        }
        {
          status == Status.playing &&
          <h1>Воспроизводится...{plaingNo}</h1>
        }
        {
          status == Status.plaied &&
          <>
          <Button variant="success" onClick={()=>setStatus(Status.showlist)}>{strings.showSyllables}</Button>
          <Button variant="success" onClick={()=>{setStatus(Status.playing)}}>{strings.playAgain}</Button>
          </>
        }
        {
          status == Status.showlist &&
          <>
            <div>{renderPlayList()}</div>
            <br/>
            <Button variant="success" onClick={()=>  setStatus(Status.params)}>{strings.toBegin}</Button>
          </>
        }
      </ListGroup.Item>
      </ListGroup>
      </>
  )
}

export default App

