import { TaskRegistry } from '@things-factory/integration-base'
import { access } from '@things-factory/utils'

var scenarioQueues = {}

async function PushQueue(step, { logger, data }) {
  var {
    params: { queueName, queueCount, accessor }
  } = step

  if (scenarioQueues[queueName] == undefined) {
    scenarioQueues[queueName] = []
  }

  var queueData = accessor ? access(accessor, data) : {}
  console.log('queueData: ', queueData)

  scenarioQueues[queueName].push(queueData)

  if (scenarioQueues[queueName].length > queueCount) {
    scenarioQueues[queueName].shift(queueCount - scenarioQueues[queueName].length)
  }

  console.log('scenarioQueues[queueName]: ', scenarioQueues[queueName])

  return {
    data: scenarioQueues[queueName]
  }
}

async function ClearQueue(step, { logger, data }) {
  var {
    params: { queueName, queueCount, accessor }
  } = step

  if (scenarioQueues[queueName] == undefined) {
    scenarioQueues[queueName] = []
  }

  scenarioQueues[queueName] = []

  return {
    data: scenarioQueues[queueName]
  }
}

PushQueue.parameterSpec = [
  {
    type: 'string',
    label: 'queue-name',
    name: 'queueName'
  },
  {
    type: 'number',
    label: 'queue-count',
    name: 'queueCount'
  },
  {
    type: 'scenario-step-input',
    label: 'accessor',
    name: 'accessor'
  }
]

ClearQueue.parameterSpec = [
  {
    type: 'string',
    label: 'queue-name',
    name: 'queueName'
  }
]

PushQueue.connectorFree = true
PushQueue.help = 'robotics/task/push-queue'
ClearQueue.connectorFree = true
ClearQueue.help = 'robotics/task/push-queue'

TaskRegistry.registerTaskHandler('push-queue', PushQueue)
TaskRegistry.registerTaskHandler('clear-queue', ClearQueue)
