import { ConnectionManager, ScenarioInstanceStatus, TaskRegistry } from '@things-factory/integration-base'
import { sleep } from '@things-factory/utils'

import { getTrackingWorkspace } from './get-tracking-workspace'

async function TrackableObjectWaitStable(step, { root, domain }) {
  var {
    connection,
    params: { minRetention }
  } = step

  var object = ConnectionManager.getConnectionInstanceByName(domain, connection) || {}
  if (!object) {
    throw new Error(`no connection : ${connection}`)
  }

  var { endpoint } = object

  var retentionCount = 0

  var targetObjectState = null
  while (true) {
    let state = root.getState()
    if (state == ScenarioInstanceStatus.STARTED /* STARTED */) {
      await sleep(1000)

      var workspace = getTrackingWorkspace(domain)
      var { engine } = workspace
      var { trackingStorage } = engine
      targetObjectState = trackingStorage.getObjectState(endpoint)
      retentionCount = targetObjectState?.retention || 0
      let targetRoi = targetObjectState?.roi || ''

      // console.log('retentionCount: ', retentionCount)
      // console.log('ROI: ', targetRoi)

      if (retentionCount > minRetention && targetRoi != '') {
        break
      }
    } else if (state == ScenarioInstanceStatus.STOPPED /* PAUSED */) {
      await sleep(1000)
    } else {
      throw new Error('scenario stopped unexpectedly')
    }
  }

  // console.log('targetObjectState: ', targetObjectState)

  return {
    data: targetObjectState
  }
}

TrackableObjectWaitStable.parameterSpec = [
  {
    type: 'number',
    name: 'minRetention',
    label: 'min-retention'
  }
]
TrackableObjectWaitStable.help = 'robotics/task/trackable-object-wait-stable'

TaskRegistry.registerTaskHandler('trackable-object-wait-stable', TrackableObjectWaitStable)
