import { Resolver, Mutation, Arg, Ctx } from 'type-graphql'
import { TrackingWorkspace, TrackingWorkspaceStatusInput } from './tracking-workspace-type'

import { ROBOTICS_OBJECT_TYPES } from '../../controllers/robotics-types'
import { ConnectionManager } from '@things-factory/integration-base'

// extend type Mutation {
//   updateTrackingWorkspaceStatus(name: String!, status: TrackingWorkspaceStatusInput!): Boolean
// }

@Resolver(TrackingWorkspace)
export class TrackingWorkspaceMutation {
  @Mutation(returns => Boolean, { description: 'To start roi configuration and get the result' })
  async updateTrackingWorkspaceStatus(
    @Arg('name', type => String, { nullable: false }) name: string,
    @Arg('status', type => TrackingWorkspaceStatusInput, { nullable: false }) status: TrackingWorkspaceStatusInput,
    @Ctx()
    context: any
  ): Promise<boolean> {
    const { domain } = context.state

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

    var { engine, params } = workspace
    var storage = engine.trackingStorage
    var { objectStatus } = status

    objectStatus.forEach(objectState => {
      var { id, state } = objectState
      var { roi, pose } = state || {}

      storage.updateObjectState(id, roi, pose, params?.poseThreshold)
    })

    return true
  }
}
