import { createElement, useContext } from 'react'
import { Button, Space } from 'antd'
import PropTypes from 'prop-types'
import { getModelByName } from '../../../database/ObjectModels'
import { AuthContext } from '../context/AuthContext'
import PlayCircleIcon from '../../Icons/PlayCircleIcon'
import PauseCircleIcon from '../../Icons/PauseCircleIcon'
import StopCircleIcon from '../../Icons/StopCircleIcon'

const findAction = (actions, name) => {
  for (const action of actions) {
    if (action.name === name) return action
    if (action.children) {
      const found = findAction(action.children, name)
      if (found) return found
    }
  }
  return null
}

const isActionDisabled = (action, objectData, userProfile, disabled) => {
  if (disabled) return true
  if (!action?.disabled) return false
  if (typeof action.disabled === 'function') {
    return action.disabled({ ...objectData, _user: userProfile })
  }
  return action.disabled
}

const PrinterControlButtons = ({ callAction, objectData, disabled }) => {
  const { userProfile } = useContext(AuthContext)
  const model = getModelByName('printer')
  const startQueueAction = findAction(model.actions, 'startQueue')
  const pauseJobAction = findAction(model.actions, 'pauseJob')
  const resumeJobAction = findAction(model.actions, 'resumeJob')
  const cancelJobAction = findAction(model.actions, 'cancelJob')

  const isPaused = objectData?.state?.type === 'paused'
  const startAction = isPaused ? resumeJobAction : startQueueAction
  const startActionName = isPaused ? 'resumeJob' : 'startQueue'

  return (
    <Space size='small'>
      <Button
        icon={createElement(PlayCircleIcon)}
        onClick={() => callAction(startActionName)}
        disabled={isActionDisabled(
          startAction,
          objectData,
          userProfile,
          disabled
        )}
        title={startAction?.label}
      />
      <Button
        icon={createElement(PauseCircleIcon)}
        onClick={() => callAction('pauseJob')}
        disabled={isActionDisabled(
          pauseJobAction,
          objectData,
          userProfile,
          disabled
        )}
        title={pauseJobAction?.label}
      />
      <Button
        icon={createElement(StopCircleIcon)}
        onClick={() => callAction('cancelJob')}
        disabled={isActionDisabled(
          cancelJobAction,
          objectData,
          userProfile,
          disabled
        )}
        title={cancelJobAction?.label}
        danger
      />
    </Space>
  )
}

PrinterControlButtons.propTypes = {
  callAction: PropTypes.func.isRequired,
  objectData: PropTypes.object.isRequired,
  disabled: PropTypes.bool,
  loading: PropTypes.bool
}

export default PrinterControlButtons
