import { Resolver, Query, FieldResolver, Root, Args, Arg, Ctx, Directive } from 'type-graphql'
import { ListParam } from '@things-factory/shell'
import { TrackableObject, TrackableObjectList } from './trackable-object-type'

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

const debug = require('debug')('aidoop:robotics:trackable-object-query')

// extend type Query {
//   trackableObjects(filters: [Filter], pagination: Pagination, sortings: [Sorting]): TrackableObjectList
//   trackableObject(name: String!): TrackableObject
// }

@Resolver(TrackableObject)
export class TrackableObjectQuery {
  @Query(returns => TrackableObject, { description: 'To fetch a trackable object' })
  async trackableObject(
    @Arg('name', type => String, { nullable: false }) name: string,
    @Ctx() context: any
  ): Promise<TrackableObject> {
    const { domain } = context.state

    var connection = ConnectionManager.getConnectionInstanceByName(domain, name)
    if (!connection || connection.discriminator !== ROBOTICS_OBJECT_TYPES.OBJECT) {
      throw Error(`TrackableObject '${name}' Not Found`)
    }

    var { poiOffset } = connection.params || {}

    return {
      ...connection,
      poiOffset
    }
  }

  @Query(returns => TrackableObjectList, { description: 'To fetch multiple trackable objects' })
  async trackableObjects(@Args() params: ListParam, @Ctx() context: any): Promise<TrackableObjectList> {
    const { domain } = context.state

    var items = Object.keys(ConnectionManager.getConnectionInstances(domain))
      .map(name => ConnectionManager.getConnectionInstanceByName(domain, name))
      .filter(connection => connection.discriminator == ROBOTICS_OBJECT_TYPES.OBJECT)
      .map(connection => {
        var { poiOffset } = connection.params || {}

        return {
          ...connection,
          poiOffset
        }
      })

    return {
      items,
      total: items.length
    }
  }
}
