"use strict";
/*
 * Tencent is pleased to support the open source community by making
 * Hippy available.
 *
 * Copyright (C) 2017-2019 THL A29 Limited, a Tencent company.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisSubscriber = exports.RedisPublisher = void 0;
/**
 * ⚠️ publish and subscribe must behind connection, otherwise redis client will change to PubSub mode, could not send AUTH command
 */
const log_1 = require("@debug-server-next/utils/log");
const redis_db_1 = require("./redis-db");
const log = new log_1.Logger('redis-pub-sub');
class RedisPublisher {
    constructor(channel) {
        this.queue = [];
        this.isConnected = false;
        if (!channel) {
            const e = new Error('channelId should not be empty');
            log.error('%s', e === null || e === void 0 ? void 0 : e.stack);
            throw e;
        }
        this.channel = channel;
        this.client = redis_db_1.RedisDB.client.duplicate();
        redis_db_1.listenRedisEvent(this.client);
        this.init();
    }
    publish(message) {
        if (this.isConnected)
            this.realPublish(message);
        else
            this.queue.push(message);
    }
    /**
     * nullish, redis could send other command in PubSub mode
     */
    disconnect() { }
    realPublish(message) {
        const msgStr = typeof message !== 'string' ? JSON.stringify(message) : message;
        try {
            this.client.publish(this.channel, msgStr);
        }
        catch (e) {
            log.error('publish %s to channel %s error: %s', msgStr, this.channel, e.stack);
        }
    }
    /**
     * init redis connection, will clear publish queue if connected
     */
    async init() {
        await this.client.connect();
        log.info('redis publisher client created, %s', this.channel);
        this.isConnected = true;
        this.queue.forEach(this.realPublish.bind(this));
    }
}
exports.RedisPublisher = RedisPublisher;
class RedisSubscriber {
    constructor(channel) {
        this.isConnected = false;
        this.operateQueue = [];
        this.unsubscribe = () => this.client.unsubscribe(this.channel);
        this.pUnsubscribe = () => this.client.pUnsubscribe(this.channel);
        /**
         * nullish, redis could send other command in PubSub mode
         */
        this.disconnect = () => { };
        if (!channel) {
            const e = new Error('channelId should not be empty');
            log.error('%s', e === null || e === void 0 ? void 0 : e.stack);
            throw e;
        }
        this.channel = channel;
        this.client = redis_db_1.RedisDB.client.duplicate();
        redis_db_1.listenRedisEvent(this.client);
        this.init();
    }
    subscribe(cb) {
        if (this.isConnected)
            this.client.subscribe(this.channel, cb);
        else
            this.operateQueue.push([this.subscribe, cb]);
    }
    /**
     * subscribe channel with glob character, such as `*`
     */
    pSubscribe(cb) {
        if (this.isConnected)
            this.client.pSubscribe(this.channel, cb);
        else
            this.operateQueue.push([this.pSubscribe, cb]);
    }
    /**
     * init redis connection, will clear subscribe queue if connected
     */
    async init() {
        if (this.isConnected)
            return;
        await this.client.connect();
        log.info('redis subscriber client created, %s', this.channel);
        this.isConnected = true;
        if (this.operateQueue) {
            this.operateQueue.forEach(([fn, cb]) => {
                fn.call(this, cb);
            });
        }
    }
}
exports.RedisSubscriber = RedisSubscriber;
