import Debug from 'debug'
import { ROBOTICS_OBJECT_TYPES } from '../robotics-types'
import { ConnectionManager, Connection } from '@things-factory/integration-base'

const debug = Debug('aidoop:robotics:robot-arm-api-decorator')

export const api = (target: Object, property: string, descriptor: TypedPropertyDescriptor<any>): any => {
  const method = descriptor.value

  descriptor.value = async function (domain, robotArmName, ...params) {
    const RobotArmAPI = this

    const connection: Connection = ConnectionManager.getConnectionInstanceByName(domain, robotArmName)
    debug('connection', robotArmName, connection)

    if (!connection || connection.discriminator !== ROBOTICS_OBJECT_TYPES.ROBOT_ARM) {
      debug(`RobotArm '${robotArmName}' Not Found`)
      throw Error(`RobotArm '${robotArmName}' Not Found`)
    }

    var { platform } = connection

    var { apis } = RobotArmAPI.getPlatform(platform)

    var m = apis[method.name]
    if (!m) {
      throw Error(`RobotArm Platform '${platform}' doesn't have API ${method.name}`)
    }

    const result = await m.call(this, connection, ...params)

    debug('api', domain.subdomain, robotArmName, method.name, params, result)

    return result
  }

  return descriptor
}
