import {Args, Resolver, Subscription} from '@nestjs/graphql'
import {Event} from '../models/Event'
import {pubsub} from '../../main'
import {UUID} from '../../global/scalars/UUID'
import {EventService} from '../event.service'

@Resolver(() => Event)
export class EventResolverS {
  constructor(
    private readonly service: EventService
  ) {}

  @Subscription(() => Event, {
    nullable: false,
    filter: async (payload, variables, context) => {
      let ret = true;

      if (ret && !!variables.organizer)
        ret = payload?.EventUpdated?._organizer === variables?.organizer
          && (context?.client?.isMaster() || context?.client?.isAdmin(variables.organizer));

      if (ret && !!variables.id)
        ret = payload?.EventUpdated?._id === variables?.id

      return ret;
    }
  })
  async EventUpdated(
    @Args('id', { type: () => UUID, nullable: true }) id: UUID,
    @Args('organizer', { type: () => UUID, nullable: true }) organizer: UUID,
  ) {
    return pubsub.asyncIterator('EventUpdated');
  }

  @Subscription(() => UUID, {
    nullable: false,
    filter: async (payload, variables, context) => {
      return payload?.organizer === variables?.organizer
        && (context?.client?.isMaster() || context?.client?.isAdmin(variables.organizer))
    }
  })
  async EventDeleted(
    @Args('organizer', { type: () => UUID, nullable: false }) organizer: UUID
  ) {
    return pubsub.asyncIterator('EventDeleted');
  }
}