import { EventSubscriber, EntitySubscriberInterface, InsertEvent, UpdateEvent } from 'typeorm'

import { pubsub, getRepository } from '@things-factory/shell'

import { ProcessGroup } from './process-group'

@EventSubscriber()
export class ProcessGroupSubscriber implements EntitySubscriberInterface<ProcessGroup> {
  listenTo() {
    return ProcessGroup
  }

  // afterInsert(event: InsertEvent<ProcessGroup>): Promise<any> | void {
  //   const processGroup = event.entity

  //   pubsub.publish('processGroup', {
  //     processGroup
  //   })
  // }

  async afterUpdate(event: UpdateEvent<ProcessGroup>): Promise<any> {
    var processGroup = event.entity

    processGroup = await getRepository(ProcessGroup).findOne({
      where: { domain: { id: processGroup.domainId }, id: processGroup.id },
      relations: ['domain']
    })

    pubsub.publish('process-group', {
      processGroup
    })
  }
}
