"use strict";
// Copyright 2017-2020 @polkadot/types authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("@polkadot/util");
const util_crypto_1 = require("@polkadot/util-crypto");
const Compact_1 = __importDefault(require("./Compact"));
const U8aFixed_1 = __importDefault(require("./U8aFixed"));
const utils_1 = require("./utils");
class BTreeSet extends Set {
    constructor(registry, valType, rawValue) {
        const ValClass = utils_1.typeToConstructor(registry, valType);
        super(BTreeSet.decodeBTreeSet(registry, ValClass, rawValue));
        this.registry = registry;
        this._ValClass = ValClass;
    }
    /**
     * Decode input to pass into constructor.
     *
     * @param ValClass - Type of the map value
     * @param value - Value to decode, one of:
     * - null
     * - undefined
     * - hex
     * - Uint8Array
     * - Set<any>, where both key and value types are either
     *   constructors or decodeable values for their types.
     * @param jsonSet
     * @internal
     */
    static decodeBTreeSet(registry, ValClass, value) {
        if (!value) {
            return new Set();
        }
        else if (util_1.isHex(value)) {
            return BTreeSet.decodeBTreeSet(registry, ValClass, util_1.hexToU8a(value));
        }
        else if (util_1.isU8a(value)) {
            return BTreeSet.decodeBTreeSetFromU8a(registry, ValClass, util_1.u8aToU8a(value));
        }
        else if (value instanceof Set) {
            return BTreeSet.decodeBTreeSetFromSet(registry, ValClass, value);
        }
        throw new Error('BTreeSet: cannot decode type');
    }
    /** @internal */
    static decodeBTreeSetFromU8a(registry, ValClass, u8a) {
        const output = new Set();
        const [offset, length] = Compact_1.default.decodeU8a(u8a);
        const types = [];
        for (let i = 0; i < length.toNumber(); i++) {
            types.push(ValClass);
        }
        const values = utils_1.decodeU8a(registry, u8a.subarray(offset), types);
        for (let i = 0; i < values.length; i++) {
            output.add(values[i]);
        }
        return output;
    }
    /** @internal */
    static decodeBTreeSetFromSet(registry, ValClass, value) {
        const output = new Set();
        value.forEach((v) => {
            let val;
            try {
                val = (v instanceof ValClass) ? v : new ValClass(registry, v);
            }
            catch (error) {
                console.error('Failed to decode BTreeSet key or value:', error.message);
                throw error;
            }
            output.add(val);
        });
        return output;
    }
    static with(valType) {
        return class extends BTreeSet {
            constructor(registry, value) {
                super(registry, valType, value);
            }
        };
    }
    /**
     * @description The length of the value when encoded as a Uint8Array
     */
    get encodedLength() {
        let len = Compact_1.default.encodeU8a(this.size).length;
        this.forEach((v) => {
            len += v.encodedLength;
        });
        return len;
    }
    /**
     * @description Returns a hash of the value
     */
    get hash() {
        return new U8aFixed_1.default(this.registry, util_crypto_1.blake2AsU8a(this.toU8a(), 256));
    }
    /**
     * @description Checks if the value is an empty value
     */
    get isEmpty() {
        return this.size === 0;
    }
    /**
     * @description Compares the value of the input to see if there is a match
     */
    eq(other) {
        return utils_1.compareSet(this, other);
    }
    /**
     * @description Returns a hex string representation of the value. isLe returns a LE (number-only) representation
     */
    toHex() {
        return util_1.u8aToHex(this.toU8a());
    }
    /**
     * @description Converts the Object to JSON, typically used for RPC transfers
     */
    toJSON() {
        const json = [];
        this.forEach((v) => {
            json.push(v.toJSON());
        });
        return json;
    }
    /**
     * @description Returns the base runtime type name for this instance
     */
    toRawType() {
        return `BTreeSet<${new this._ValClass(this.registry).toRawType()}>`;
    }
    /**
     * @description Returns the string representation of the value
     */
    toString() {
        return JSON.stringify(this.toJSON());
    }
    /**
     * @description Encodes the value as a Uint8Array as per the SCALE specifications
     * @param isBare true when the value has none of the type-specific prefixes (internal)
     */
    toU8a(isBare) {
        const encoded = new Array();
        if (!isBare) {
            encoded.push(Compact_1.default.encodeU8a(this.size));
        }
        this.forEach((v) => {
            encoded.push(v.toU8a(isBare));
        });
        return util_1.u8aConcat(...encoded);
    }
}
exports.default = BTreeSet;
