import { ROBOTICS_OBJECT_TYPES } from '../../../controllers/robotics-types'
import { ConnectionManager } from '@things-factory/integration-base'
import { config, logger } from '@things-factory/env'
import spawn from 'await-spawn'
import { DataBridgeConnectionManager } from '../../../controllers/data-bridge/data-bridge-manager'

const visionConfig = config.get('vision', {})
const program = visionConfig.camera?.cameraCalibrator?.program

export const calibrateCameraParameterResolver = {
  async calibrateCameraParameter(_: any, { name }, context: any) {
    const { domain } = context.state

    var camera = ConnectionManager.getConnectionInstanceByName(domain, name)
    if (!camera || camera.discriminator !== ROBOTICS_OBJECT_TYPES.CAMERA) {
      throw Error(`Tracking Camera '${name}' Not Found`)
    }

    let activeApp = DataBridgeConnectionManager.getActive()
    if (activeApp === '' || activeApp === name) {
      // TODO: control to run multiple python applications here
      DataBridgeConnectionManager.set(name, 'start')
    }

    var executable = program[0]
    var params = [...program.slice(1), name]

    var cameraParameter = await spawn(executable, params)

    logger.info(`calibration matrix:\n'${cameraParameter?.toString()}'`)

    return JSON.parse(cameraParameter.toString())
  }
}
