"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _RedisCluster_instances, _RedisCluster_options, _RedisCluster_slots, _RedisCluster_Multi, _RedisCluster_handleCommandError;
Object.defineProperty(exports, "__esModule", { value: true });
const commands_1 = require("./commands");
const cluster_slots_1 = require("./cluster-slots");
const commander_1 = require("../commander");
const events_1 = require("events");
const multi_command_1 = require("./multi-command");
class RedisCluster extends events_1.EventEmitter {
    constructor(options) {
        super();
        _RedisCluster_instances.add(this);
        _RedisCluster_options.set(this, void 0);
        _RedisCluster_slots.set(this, void 0);
        _RedisCluster_Multi.set(this, void 0);
        __classPrivateFieldSet(this, _RedisCluster_options, options, "f");
        __classPrivateFieldSet(this, _RedisCluster_slots, new cluster_slots_1.default(options, err => this.emit('error', err)), "f");
        __classPrivateFieldSet(this, _RedisCluster_Multi, multi_command_1.default.extend(options), "f");
    }
    static extractFirstKey(command, originalArgs, redisArgs) {
        if (command.FIRST_KEY_INDEX === undefined) {
            return undefined;
        }
        else if (typeof command.FIRST_KEY_INDEX === 'number') {
            return redisArgs[command.FIRST_KEY_INDEX];
        }
        return command.FIRST_KEY_INDEX(...originalArgs);
    }
    static create(options) {
        return new ((0, commander_1.extendWithModulesAndScripts)({
            BaseClass: RedisCluster,
            modules: options === null || options === void 0 ? void 0 : options.modules,
            modulesCommandsExecutor: RedisCluster.prototype.commandsExecutor,
            scripts: options === null || options === void 0 ? void 0 : options.scripts,
            scriptsExecutor: RedisCluster.prototype.scriptsExecutor
        }))(options);
    }
    duplicate(overrides) {
        return new (Object.getPrototypeOf(this).constructor)({
            ...__classPrivateFieldGet(this, _RedisCluster_options, "f"),
            ...overrides
        });
    }
    async connect() {
        return __classPrivateFieldGet(this, _RedisCluster_slots, "f").connect();
    }
    async commandsExecutor(command, args) {
        const { args: redisArgs, options } = (0, commander_1.transformCommandArguments)(command, args);
        return (0, commander_1.transformCommandReply)(command, await this.sendCommand(RedisCluster.extractFirstKey(command, args, redisArgs), command.IS_READ_ONLY, redisArgs, options, command.BUFFER_MODE), redisArgs.preserve);
    }
    async sendCommand(firstKey, isReadonly, args, options, bufferMode, redirections = 0) {
        const client = __classPrivateFieldGet(this, _RedisCluster_slots, "f").getClient(firstKey, isReadonly);
        try {
            return await client.sendCommand(args, options, bufferMode);
        }
        catch (err) {
            const shouldRetry = await __classPrivateFieldGet(this, _RedisCluster_instances, "m", _RedisCluster_handleCommandError).call(this, err, client, redirections);
            if (shouldRetry === true) {
                return this.sendCommand(firstKey, isReadonly, args, options, bufferMode, redirections + 1);
            }
            else if (shouldRetry) {
                return shouldRetry.sendCommand(args, options, bufferMode);
            }
            throw err;
        }
    }
    async scriptsExecutor(script, args) {
        const { args: redisArgs, options } = (0, commander_1.transformCommandArguments)(script, args);
        return (0, commander_1.transformCommandReply)(script, await this.executeScript(script, args, redisArgs, options), redisArgs.preserve);
    }
    async executeScript(script, originalArgs, redisArgs, options, redirections = 0) {
        const client = __classPrivateFieldGet(this, _RedisCluster_slots, "f").getClient(RedisCluster.extractFirstKey(script, originalArgs, redisArgs), script.IS_READ_ONLY);
        try {
            return await client.executeScript(script, redisArgs, options, script.BUFFER_MODE);
        }
        catch (err) {
            const shouldRetry = await __classPrivateFieldGet(this, _RedisCluster_instances, "m", _RedisCluster_handleCommandError).call(this, err, client, redirections);
            if (shouldRetry === true) {
                return this.executeScript(script, originalArgs, redisArgs, options, redirections + 1);
            }
            else if (shouldRetry) {
                return shouldRetry.executeScript(script, redisArgs, options, script.BUFFER_MODE);
            }
            throw err;
        }
    }
    multi(routing) {
        return new (__classPrivateFieldGet(this, _RedisCluster_Multi, "f"))(async (commands, firstKey, chainId) => {
            return __classPrivateFieldGet(this, _RedisCluster_slots, "f")
                .getClient(firstKey)
                .multiExecutor(commands, chainId);
        }, routing);
    }
    getMasters() {
        return __classPrivateFieldGet(this, _RedisCluster_slots, "f").getMasters();
    }
    getSlotMaster(slot) {
        return __classPrivateFieldGet(this, _RedisCluster_slots, "f").getSlotMaster(slot);
    }
    disconnect() {
        return __classPrivateFieldGet(this, _RedisCluster_slots, "f").disconnect();
    }
}
exports.default = RedisCluster;
_RedisCluster_options = new WeakMap(), _RedisCluster_slots = new WeakMap(), _RedisCluster_Multi = new WeakMap(), _RedisCluster_instances = new WeakSet(), _RedisCluster_handleCommandError = async function _RedisCluster_handleCommandError(err, client, redirections) {
    var _a;
    if (redirections > ((_a = __classPrivateFieldGet(this, _RedisCluster_options, "f").maxCommandRedirections) !== null && _a !== void 0 ? _a : 16)) {
        throw err;
    }
    if (err.message.startsWith('ASK')) {
        const url = err.message.substring(err.message.lastIndexOf(' ') + 1);
        let node = __classPrivateFieldGet(this, _RedisCluster_slots, "f").getNodeByUrl(url);
        if (!node) {
            await __classPrivateFieldGet(this, _RedisCluster_slots, "f").rediscover(client);
            node = __classPrivateFieldGet(this, _RedisCluster_slots, "f").getNodeByUrl(url);
            if (!node) {
                throw new Error(`Cannot find node ${url}`);
            }
        }
        await node.client.asking();
        return node.client;
    }
    else if (err.message.startsWith('MOVED')) {
        await __classPrivateFieldGet(this, _RedisCluster_slots, "f").rediscover(client);
        return true;
    }
    throw err;
};
(0, commander_1.extendWithCommands)({
    BaseClass: RedisCluster,
    commands: commands_1.default,
    executor: RedisCluster.prototype.commandsExecutor
});
