import { deref } from "../deref";
import { ListSchema } from "./ListSchema";
import { MapSchema } from "./MapSchema";
import { Schema } from "./Schema";
import { SCHEMA } from "./sentinels";
import { SimpleSchema } from "./SimpleSchema";
import { StructureSchema } from "./StructureSchema";
export class NormalizedSchema {
    ref;
    memberName;
    static symbol = Symbol.for("@smithy/nor");
    symbol = NormalizedSchema.symbol;
    name;
    schema;
    _isMemberSchema;
    traits;
    memberTraits;
    normalizedTraits;
    constructor(ref, memberName) {
        this.ref = ref;
        this.memberName = memberName;
        const traitStack = [];
        let _ref = ref;
        let schema = ref;
        this._isMemberSchema = false;
        while (Array.isArray(_ref)) {
            traitStack.push(_ref[1]);
            _ref = _ref[0];
            schema = deref(_ref);
            this._isMemberSchema = true;
        }
        if (traitStack.length > 0) {
            this.memberTraits = {};
            for (let i = traitStack.length - 1; i >= 0; --i) {
                const traitSet = traitStack[i];
                Object.assign(this.memberTraits, NormalizedSchema.translateTraits(traitSet));
            }
        }
        else {
            this.memberTraits = 0;
        }
        if (schema instanceof NormalizedSchema) {
            const computedMemberTraits = this.memberTraits;
            Object.assign(this, schema);
            this.memberTraits = Object.assign({}, computedMemberTraits, schema.getMemberTraits(), this.getMemberTraits());
            this.normalizedTraits = void 0;
            this.memberName = memberName ?? schema.memberName;
            return;
        }
        this.schema = deref(schema);
        if (this.schema && typeof this.schema === "object") {
            this.traits = this.schema?.traits ?? {};
        }
        else {
            this.traits = 0;
        }
        this.name =
            (this.schema instanceof Schema ? this.schema.getName?.() : void 0) ?? this.memberName ?? this.getSchemaName();
        if (this._isMemberSchema && !memberName) {
            throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`);
        }
    }
    static [Symbol.hasInstance](lhs) {
        return Schema[Symbol.hasInstance].bind(this)(lhs);
    }
    static of(ref) {
        if (ref instanceof NormalizedSchema) {
            return ref;
        }
        if (Array.isArray(ref)) {
            const [ns, traits] = ref;
            if (ns instanceof NormalizedSchema) {
                Object.assign(ns.getMergedTraits(), NormalizedSchema.translateTraits(traits));
                return ns;
            }
            throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`);
        }
        return new NormalizedSchema(ref);
    }
    static translateTraits(indicator) {
        if (typeof indicator === "object") {
            return indicator;
        }
        indicator = indicator | 0;
        const traits = {};
        let i = 0;
        for (const trait of [
            "httpLabel",
            "idempotent",
            "idempotencyToken",
            "sensitive",
            "httpPayload",
            "httpResponseCode",
            "httpQueryParams",
        ]) {
            if (((indicator >> i++) & 1) === 1) {
                traits[trait] = 1;
            }
        }
        return traits;
    }
    getSchema() {
        if (this.schema instanceof NormalizedSchema) {
            Object.assign(this, { schema: this.schema.getSchema() });
            return this.schema;
        }
        if (this.schema instanceof SimpleSchema) {
            return deref(this.schema.schemaRef);
        }
        return deref(this.schema);
    }
    getName(withNamespace = false) {
        if (!withNamespace) {
            if (this.name && this.name.includes("#")) {
                return this.name.split("#")[1];
            }
        }
        return this.name || undefined;
    }
    getMemberName() {
        if (!this.isMemberSchema()) {
            throw new Error(`@smithy/core/schema - non-member schema: ${this.getName(true)}`);
        }
        return this.memberName;
    }
    isMemberSchema() {
        return this._isMemberSchema;
    }
    isUnitSchema() {
        return this.getSchema() === "unit";
    }
    isListSchema() {
        const inner = this.getSchema();
        if (typeof inner === "number") {
            return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER;
        }
        return inner instanceof ListSchema;
    }
    isMapSchema() {
        const inner = this.getSchema();
        if (typeof inner === "number") {
            return inner >= SCHEMA.MAP_MODIFIER && inner <= 0b1111_1111;
        }
        return inner instanceof MapSchema;
    }
    isStructSchema() {
        const inner = this.getSchema();
        return (inner !== null && typeof inner === "object" && "members" in inner) || inner instanceof StructureSchema;
    }
    isBlobSchema() {
        return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB;
    }
    isTimestampSchema() {
        const schema = this.getSchema();
        return typeof schema === "number" && schema >= SCHEMA.TIMESTAMP_DEFAULT && schema <= SCHEMA.TIMESTAMP_EPOCH_SECONDS;
    }
    isDocumentSchema() {
        return this.getSchema() === SCHEMA.DOCUMENT;
    }
    isStringSchema() {
        return this.getSchema() === SCHEMA.STRING;
    }
    isBooleanSchema() {
        return this.getSchema() === SCHEMA.BOOLEAN;
    }
    isNumericSchema() {
        return this.getSchema() === SCHEMA.NUMERIC;
    }
    isBigIntegerSchema() {
        return this.getSchema() === SCHEMA.BIG_INTEGER;
    }
    isBigDecimalSchema() {
        return this.getSchema() === SCHEMA.BIG_DECIMAL;
    }
    isStreaming() {
        const streaming = !!this.getMergedTraits().streaming;
        if (streaming) {
            return true;
        }
        return this.getSchema() === SCHEMA.STREAMING_BLOB;
    }
    isIdempotencyToken() {
        if (this.normalizedTraits) {
            return !!this.normalizedTraits.idempotencyToken;
        }
        for (const traits of [this.traits, this.memberTraits]) {
            if (typeof traits === "number") {
                if ((traits & 0b0100) === 0b0100) {
                    return true;
                }
            }
            else if (typeof traits === "object") {
                if (!!traits.idempotencyToken) {
                    return true;
                }
            }
        }
        return false;
    }
    getMergedTraits() {
        return (this.normalizedTraits ??
            (this.normalizedTraits = {
                ...this.getOwnTraits(),
                ...this.getMemberTraits(),
            }));
    }
    getMemberTraits() {
        return NormalizedSchema.translateTraits(this.memberTraits);
    }
    getOwnTraits() {
        return NormalizedSchema.translateTraits(this.traits);
    }
    getKeySchema() {
        if (this.isDocumentSchema()) {
            return this.memberFrom([SCHEMA.DOCUMENT, 0], "key");
        }
        if (!this.isMapSchema()) {
            throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`);
        }
        const schema = this.getSchema();
        if (typeof schema === "number") {
            return this.memberFrom([0b0011_1111 & schema, 0], "key");
        }
        return this.memberFrom([schema.keySchema, 0], "key");
    }
    getValueSchema() {
        const schema = this.getSchema();
        if (typeof schema === "number") {
            if (this.isMapSchema()) {
                return this.memberFrom([0b0011_1111 & schema, 0], "value");
            }
            else if (this.isListSchema()) {
                return this.memberFrom([0b0011_1111 & schema, 0], "member");
            }
        }
        if (schema && typeof schema === "object") {
            if (this.isStructSchema()) {
                throw new Error(`may not getValueSchema() on structure ${this.getName(true)}`);
            }
            const collection = schema;
            if ("valueSchema" in collection) {
                if (this.isMapSchema()) {
                    return this.memberFrom([collection.valueSchema, 0], "value");
                }
                else if (this.isListSchema()) {
                    return this.memberFrom([collection.valueSchema, 0], "member");
                }
            }
        }
        if (this.isDocumentSchema()) {
            return this.memberFrom([SCHEMA.DOCUMENT, 0], "value");
        }
        throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`);
    }
    hasMemberSchema(member) {
        if (this.isStructSchema()) {
            const struct = this.getSchema();
            return struct.memberNames.includes(member);
        }
        return false;
    }
    getMemberSchema(member) {
        if (this.isStructSchema()) {
            const struct = this.getSchema();
            if (!struct.memberNames.includes(member)) {
                throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${member}.`);
            }
            const i = struct.memberNames.indexOf(member);
            const memberSchema = struct.memberList[i];
            return this.memberFrom(Array.isArray(memberSchema) ? memberSchema : [memberSchema, 0], member);
        }
        if (this.isDocumentSchema()) {
            return this.memberFrom([SCHEMA.DOCUMENT, 0], member);
        }
        throw new Error(`@smithy/core/schema - ${this.getName(true)} has no members.`);
    }
    getMemberSchemas() {
        const buffer = {};
        try {
            for (const [k, v] of this.structIterator()) {
                buffer[k] = v;
            }
        }
        catch (ignored) { }
        return buffer;
    }
    getEventStreamMember() {
        if (this.isStructSchema()) {
            for (const [memberName, memberSchema] of this.structIterator()) {
                if (memberSchema.isStreaming() && memberSchema.isStructSchema()) {
                    return memberName;
                }
            }
        }
        return "";
    }
    *structIterator() {
        if (this.isUnitSchema()) {
            return;
        }
        if (!this.isStructSchema()) {
            throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");
        }
        const struct = this.getSchema();
        for (let i = 0; i < struct.memberNames.length; ++i) {
            yield [struct.memberNames[i], this.memberFrom([struct.memberList[i], 0], struct.memberNames[i])];
        }
    }
    memberFrom(memberSchema, memberName) {
        if (memberSchema instanceof NormalizedSchema) {
            return Object.assign(memberSchema, {
                memberName,
                _isMemberSchema: true,
            });
        }
        return new NormalizedSchema(memberSchema, memberName);
    }
    getSchemaName() {
        const schema = this.getSchema();
        if (typeof schema === "number") {
            const _schema = 0b0011_1111 & schema;
            const container = 0b1100_0000 & schema;
            const type = Object.entries(SCHEMA).find(([, value]) => {
                return value === _schema;
            })?.[0] ?? "Unknown";
            switch (container) {
                case SCHEMA.MAP_MODIFIER:
                    return `${type}Map`;
                case SCHEMA.LIST_MODIFIER:
                    return `${type}List`;
                case 0:
                    return type;
            }
        }
        return "Unknown";
    }
}
