import { Http, isNullOrUndefined } from "@intelligentgraphics/ig.utilities";
const handleResponses = (res) => {
    if (typeof res === "object" && "state" in res) {
        if (res.state !== "SUCCESS") {
            throw new Error(`Received an invalid response state from the gfx service "${res.state}"`);
        }
    }
    return res;
};
export class Service {
    constructor(options) {
        this.options = options;
        this.requester = new Http.Service({
            baseUrl: options.basePath,
            defaults: {
                json: true,
            },
            middlewares: [
                (url, options, next) => next(url, options).then(handleResponses),
            ],
        });
    }
    async getProducts() {
        const res = await this.requester.post(`Get/Products`, {
            Scope: this.options.scope,
            Password: this.options.password,
        });
        return res.map(product => ({
            articleId: "nativeId" in product ? product.nativeId : product.NativeId,
            product: "product" in product ? product.product : product.Product,
        }));
    }
    configure(articleId, configuration, previousHashes) {
        return this.configureWithScope({
            articleId,
            configuration,
            hashes: previousHashes,
            ...this.createScopeBody(),
        });
    }
    configureWithScope({ articleId, configuration, hashes: previousHashes, scope, password, }) {
        const hashes = previousHashes === undefined
            ? {}
            : {
                VisualHash: previousHashes.visual,
                GeometricHash: previousHashes.geometric,
                PbrHash: previousHashes.pbr,
            };
        return this.requester.post(`Configure`, {
            Password: password,
            Scope: scope,
            ...hashes,
            Product: articleId,
            State: configuration,
        });
    }
    //#endregion
    createScopeBody() {
        if (isNullOrUndefined(this.options.scope) ||
            isNullOrUndefined(this.options.password)) {
            throw new Error(`This operation requires a scope and password to be provided`);
        }
        return {
            scope: this.options.scope,
            password: this.options.password,
        };
    }
}
