import React, { useEffect, useState } from 'react'
import { RouteComponentProps, useHistory } from 'react-router-dom'
import { getClient, killSession, restartSession } from '../api'
import { SessionPictures } from './SessionPictures'
import { Button } from 'antd'

type Props = RouteComponentProps<{ clientId: string }>

export const Session = (props: Props) => {
  const history = useHistory()
  const { clientId } = props.match.params
  const [active, setActive] = useState(false)

  const handleStartSession = async () => {
    setActive(true)
  }

  const handleRestartSession = async () => {
    setActive(false)
    await restartSession(clientId)
    setActive(true)
  }

  const handleExit = async () => {
    history.push('/')
  }

  const handleNuke = async () => {
    await killSession(clientId)
    history.push('/')
  }

  useEffect(() => {
    const get = async () => {
      const { activeSession } = await getClient(clientId)
      if (activeSession) setActive(true)
    }

    get()
  })

  return (
    <div>
      <h1>Session for {clientId}</h1>
      <button onClick={handleStartSession}>Capture</button>
      <div className="controls">
        <Button disabled={!active} onClick={handleRestartSession}>
          Retry Capture
        </Button>
        <Button disabled={!active} onClick={handleNuke}>
          Nuke Session
        </Button>
        <Button onClick={handleExit}>Exit Session</Button>
        {active && <SessionPictures clientId={clientId} />}
      </div>
    </div>
  )
}
