var _this = this;
import * as tslib_1 from "tslib";
import { generateId, Obj } from "@intelligentgraphics/ig.utilities";
import { IGXE, } from "@intelligentgraphics/igd.productdata";
export var createProductDataManager = function (_a) {
    var file = _a.file, gfxService = _a.gfxService;
    return tslib_1.__awaiter(_this, void 0, void 0, function () {
        var basket, extractFromCatalogItem, getBasketItemOrThrow, addArticle, removeArticle, duplicateArticle, getArticleConfiguration, getArticlePropertyList, setPropValue, setPropValues, getGfxRepresentation, getIGXCRepresentation, _b;
        return tslib_1.__generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    basket = new Map();
                    extractFromCatalogItem = function (key, comId) {
                        var article = basket.get(comId);
                        if (article === undefined) {
                            return Promise.reject(new Error("Can not find info \"" + key + "\" because article \"" + comId + "\" does not exist"));
                        }
                        return Promise.resolve(article.catalogItem[key]);
                    };
                    getBasketItemOrThrow = function (comId) {
                        var basketItem = basket.get(comId);
                        if (basketItem === undefined) {
                            throw new Error("Can not find informations for article \"" + comId + "\"");
                        }
                        return basketItem;
                    };
                    addArticle = function (articleNo, initialConfiguration, source) {
                        var article = {
                            id: generateId(),
                            configuration: file.getDefaultConfiguration(articleNo.baseArticleNumber),
                            catalogItem: articleNo.catalogItem,
                            properties: Obj.deepClone(file.getProperties(articleNo.baseArticleNumber)),
                            articleId: articleNo.baseArticleNumber,
                        };
                        basket.set(article.id, article);
                        return Promise.resolve(article.id);
                    };
                    removeArticle = function (comID) {
                        return Promise.resolve(basket.delete(comID));
                    };
                    duplicateArticle = function (comID) {
                        throw new Error("Method not implemented.");
                    };
                    getArticleConfiguration = function (comId) {
                        var configuration = getBasketItemOrThrow(comId).configuration;
                        return Promise.resolve(configuration);
                    };
                    getArticlePropertyList = function (comId) {
                        var properties = getBasketItemOrThrow(comId).properties;
                        return Promise.resolve(Object.getOwnPropertyNames(properties).map(function (prop) { return properties[prop]; }));
                    };
                    setPropValue = function (comID, changedPropKey, newPropValue) {
                        var _a;
                        return setPropValues(comID, (_a = {}, _a[changedPropKey] = newPropValue, _a));
                    };
                    setPropValues = function (comID, values) {
                        var e_1, _a;
                        var changes = IGXE.normalizePropertyValueChanges(values);
                        var basketItem = getBasketItemOrThrow(comID);
                        basketItem.configuration = tslib_1.__assign({}, basketItem.configuration);
                        try {
                            for (var changes_1 = tslib_1.__values(changes), changes_1_1 = changes_1.next(); !changes_1_1.done; changes_1_1 = changes_1.next()) {
                                var _b = changes_1_1.value, key = _b.key, value = _b.value;
                                basketItem.configuration[key] = value;
                                basketItem.properties[key] = tslib_1.__assign({}, basketItem.properties[key], { Value: value });
                            }
                        }
                        catch (e_1_1) { e_1 = { error: e_1_1 }; }
                        finally {
                            try {
                                if (changes_1_1 && !changes_1_1.done && (_a = changes_1.return)) _a.call(changes_1);
                            }
                            finally { if (e_1) throw e_1.error; }
                        }
                        return Promise.resolve();
                    };
                    getGfxRepresentation = function (comID) {
                        return Promise.resolve(undefined);
                    };
                    getIGXCRepresentation = function (comId) {
                        throw new Error("Method not implemented.");
                    };
                    _b = [{ is: function () { return false; }, addArticle: addArticle,
                            removeArticle: removeArticle,
                            duplicateArticle: duplicateArticle,
                            getArticleConfiguration: getArticleConfiguration, getArticleCatalogImage: function (comId) {
                                return extractFromCatalogItem("Image", comId);
                            }, getArticleID: function (comId) { return extractFromCatalogItem("ID", comId); }, getArticleShortText: function (comId) {
                                return extractFromCatalogItem("Caption", comId).then(function (data) {
                                    return typeof data === "string" ? [data] : data;
                                });
                            }, getArticleVariantText: function (comId) { return Promise.resolve([]); }, getArticleLongText: function (comId) {
                                return extractFromCatalogItem("Description", comId).then(function (data) {
                                    return typeof data === "string" ? [data] : data;
                                });
                            }, getArticleVariantCode: function (comId) { return Promise.resolve(""); }, getArticleName: function (comId) { return Promise.resolve(undefined); }, getArticleManufacturerID: function (comId) { return Promise.resolve(""); }, getArticleManufacturerName: function (comId) { return Promise.resolve(""); }, getArticleProgramID: function (comId) { return Promise.resolve(""); }, getArticleProgramName: function (comId) { return Promise.resolve(""); }, getArticlePrices: function (comId) { return Promise.resolve([]); }, getArticlePropertyList: getArticlePropertyList, getArticleType: function () { return Promise.resolve("graphical"); }, getArticleCategories: function () { return Promise.resolve({}); }, isGeometricProperty: function () { return Promise.resolve(true); }, getSubArticleIDs: function () { return Promise.resolve([]); }, getConnectedArticles: function () { return Promise.resolve([]); }, setPropValue: setPropValue,
                            setPropValues: setPropValues,
                            getGfxRepresentation: getGfxRepresentation,
                            getIGXCRepresentation: getIGXCRepresentation, getArticlePlacement: function () { return Promise.resolve(undefined); } }];
                    return [4 /*yield*/, createGfxServiceConnection(gfxService, basket)];
                case 1: return [2 /*return*/, tslib_1.__assign.apply(void 0, _b.concat([(_c.sent())]))];
            }
        });
    });
};
var createGfxServiceConnection = function (service, basket) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
    var getGfxRepresentation;
    var _this = this;
    return tslib_1.__generator(this, function (_a) {
        getGfxRepresentation = function (comId, options) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
            var basketItem, igxc;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        basketItem = basket.get(comId);
                        return [4 /*yield*/, service.configure(basketItem.articleId, basketItem.configuration, options.visualHash === undefined &&
                                options.geometricHash === undefined
                                ? undefined
                                : {
                                    geometric: options.geometricHash,
                                    visual: options.visualHash,
                                })];
                    case 1:
                        igxc = _a.sent();
                        return [2 /*return*/, {
                                scene: igxc,
                            }];
                }
            });
        }); };
        return [2 /*return*/, {
                getGfxRepresentation: getGfxRepresentation,
            }];
    });
}); };
var createImpressionProviderExtensions = function (file, basket) {
    // public getMaxZoomLevel(comId: string, imageKey: string): Promise<number> {
    // 	return Promise.resolve(0);
    // }
    // public getAllImpressions(comId: string): Promise<IImpressionEntry[]> {
    // 	const {
    // 		catalogItem: { ID },
    // 		configuration,
    // 	} = this.getItem(comId);
    // 	const { model, images } = this.file.getArticleMetaData(ID);
    // 	const tHash = btoa(JSON.stringify(this.basket[comId].configuration));
    // 	return Promise.resolve(images.map(key => ({ key, hash: key + tHash })));
    // }
    // public async getAllTiles(
    // 	comId: string,
    // 	imageKey: string,
    // 	level?: number,
    // ): Promise<string[][]> {
    // 	return [[await this.getTileImageUrl(comId, imageKey, level, 0, 0)]];
    // }
    // public async getTileImageUrl(
    // 	comId: string,
    // 	imageKey: string,
    // 	level?: number,
    // 	row?: number,
    // 	column?: number,
    // ) {
    // 	const {
    // 		catalogItem: { ID },
    // 		configuration,
    // 	} = this.getItem(comId);
    // 	const { model, images } = this.file.getArticleMetaData(ID);
    // 	const {
    // 		[imageKey]: { image },
    // 	} = await Http.post(
    // 		`${this.settings.ServiceUrl}${this.settings.SupplierId}/GetImage`,
    // 		{
    // 			password: this.settings.Password,
    // 			model,
    // 			product: ID,
    // 			state: configuration,
    // 			images: [imageKey],
    // 		},
    // 		{
    // 			headers: {
    // 				"Content-Type":
    // 					"application/x-www-form-urlencoded; charset=UTF-8",
    // 			},
    // 		},
    // 	).then(JSON.parse);
    // 	if (!image) {
    // 		throw new Error(
    // 			`Could not load mds image url for article ${ID} with the configuration: ${JSON.stringify(
    // 				configuration,
    // 			)}`,
    // 		);
    // 	}
    // 	return image;
    // }
    // public getCompleteImageUrl(comId: string, imageKey: string, level: number) {
    // 	return this.getTileImageUrl(comId, imageKey, level, 0, 0);
    // }
    return {
        is: function (type) {
            return type === "ImpressionProvider";
        },
    };
};
