"use strict";
// Copyright 2017-2020 @polkadot/rpc-core authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
Object.defineProperty(exports, "__esModule", { value: true });
const rxjs_1 = require("rxjs");
const DELAY = 1750;
/** @internal */
function refCountDelayInner(source) {
    let connected = 0; // 0 = disconnected, 1 = disconnecting, 2 = connecting, 3 = connected
    let refCount = 0;
    let con = rxjs_1.Subscription.EMPTY;
    let sched = rxjs_1.Subscription.EMPTY;
    return new rxjs_1.Observable((ob) => {
        source.subscribe(ob);
        if (refCount++ === 0) {
            if (connected === 1) {
                connected = 3;
                sched.unsubscribe();
            }
            else {
                con = source.connect();
                connected = 3;
            }
        }
        return () => {
            if (--refCount === 0) {
                if (connected === 2) {
                    connected = 0;
                    sched.unsubscribe();
                }
                else {
                    // connected === 3
                    connected = 1;
                    sched = rxjs_1.asapScheduler.schedule(() => {
                        con.unsubscribe();
                        connected = 0;
                    }, DELAY);
                }
            }
        };
    });
}
/** @internal */
function refCountDelay() {
    return refCountDelayInner;
}
exports.refCountDelay = refCountDelay;
