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

import { ROBOTICS_OBJECT_TYPES } from '../../controllers/robotics-types'
import { TrackingEngineImpl } from '../../controllers/tracking-engine'

export class TrackingWorkspace implements Connector {
  async ready(connectionConfigs) {
    await Promise.all(connectionConfigs.map(this.connect.bind(this)))

    ConnectionManager.logger.info('tracking-workspace connections are ready')
  }

  async connect(connection) {
    var { name } = connection
    var engine = new TrackingEngineImpl(name)

    ConnectionManager.addConnectionInstance(connection, {
      discriminator: ROBOTICS_OBJECT_TYPES.WORKSPACE,
      ...connection,
      engine
    })

    /* IMPROVE-ME 최초 시작시점에 다른 커넥션들이 완료될 시간을 1초 정도 벌어주자. */
    await sleep(1000)

    engine.start({
      onstdout: stdout => {
        ConnectionManager.logger.info(stdout.toString('utf8'))
      },
      onstderr: stderr => {
        ConnectionManager.logger.error(stderr.toString('utf8'))
        console.error(stderr.toString('utf8'))
      },
      onexit: exitcode => {
        /* 비정상적 종료시에는 커넥션을 직접 끊어준다. */
        ConnectionManager.logger.error(
          `tracking-workspace('${name}') connection will be disconnected due to onexit from tracking engine.`
        )
        ConnectionManager.getConnectionInstance(connection) && this.disconnect(connection)
      }
    })

    ConnectionManager.logger.info(
      `tracking-workspace connection(${connection.name}:${connection.endpoint}) is connected`
    )
  }

  async disconnect(connection: Connection) {
    var { engine } = ConnectionManager.removeConnectionInstance(connection)
    engine && engine.stop()

    ConnectionManager.logger.info(`tracking-workspace connection(${connection.name}) is disconnected`)
  }

  get parameterSpec() {
    return [
      {
        type: 'checkbox',
        label: 'camera stream',
        name: 'checkVideoStream'
      },
      {
        type: 'select',
        label: 'detection-method',
        name: 'detectionMethod',
        property: {
          options: ['', 'Aruco', 'Box', 'Pack']
        }
      },
      {
        type: 'offset-pose-simple',
        name: 'poseThreshold',
        label: 'pose-threshold'
      },
      {
        type: 'workspace-status',
        label: 'workspace status',
        name: 'workspaceStatus'
      }
    ]
  }

  get taskPrefixes() {
    return ['tracking-ws']
  }

  get help() {
    return 'robotics/connector/workspace'
  }
}

ConnectionManager.registerConnector('tracking-workspace', new TrackingWorkspace())
