import { PubSub } from 'graphql-subscriptions';
import { AmqpPubSub } from 'graphql-rabbitmq-subscriptions';
import { ConsoleLogger, IConsoleLoggerSettings } from '@cdm-logger/server/lib';
import * as Logger from 'bunyan';
import { Service, Container, Injector, ConfigService } from '@gapi/core';
import { AmqpConfigService } from './amqp-config.service';
import { AmqpConfig } from './amqp.interface';

export let pubsub: PubSub | AmqpPubSub;

const logger: Logger = ConsoleLogger.create('<app name>', <IConsoleLoggerSettings>{
    level: 'info', // Optional: default 'info' ('trace'|'info'|'debug'|'warn'|'error'|'fatal')
    mode: 'raw' // Optional: default 'short' ('short'|'long'|'dev'|'raw')
});

@Service()
export class GapiPubSubService {
    sub: AmqpPubSub | PubSub;
    constructor(
        private config: AmqpConfig,
        private pubSub?: AmqpPubSub | PubSub | any
    ) {
        if (pubSub) {
            return this.sub = pubSub;
        } else if (process.env.NODE_ENV === 'production') {
            this.sub = new AmqpPubSub({
                config: {
                    host: this.config.host,
                    port: this.config.port,
                },
                logger,
            });
        } else {
            this.sub = new PubSub();
        }
    }
    asyncIterator<T>(event): AsyncIterator<T> {
        return this.sub.asyncIterator<T>(event);
    }
    publish(signal: string, data: any): boolean {
        return this.sub.publish(signal, data);
    }
}



