"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var index_1 = require("../index");
index_1.registerCommercePlugin({
    name: 'Swell',
    id: '@builder.io/ecome-swell',
    settings: [
        {
            name: 'storeId',
            type: 'string',
            required: true,
            helperText: 'Get your Store ID from swell store settings https://swell.store/docs/api/?javascript#authentication',
        },
        {
            name: 'secretKey',
            type: 'string',
            required: true,
            helperText: 'Get your Secret key from swell store settings https://swell.store/docs/api/?javascript#authentication',
        },
    ],
    ctaText: "Connect your swell.is store",
    onSave: function (actions // update plugin setting
    ) { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, actions.updateSettings({
                        hasConnected: true,
                    })];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); },
}, function (settings) {
    var basicCache = new Map();
    var baseUrl = function (url) {
        return 'https://builder.io/api/v1/proxy-api?url=' +
            encodeURIComponent('https://api.swell.store/' + url);
    };
    var headers = {
        Authorization: "Basic " + btoa(settings.get('storeId') + ":" + settings.get('secretKey')),
        Accept: 'application/json',
        'Content-Type': 'application/json',
    };
    var transformProduct = function (product) {
        var _a;
        return (__assign({ id: product.id, title: product.name, handle: product.slug }, (product.images && {
            image: {
                src: (_a = product.images[0]) === null || _a === void 0 ? void 0 : _a.file.url,
            },
        })));
    };
    return {
        getProductById: function (id) {
            return __awaiter(this, void 0, void 0, function () {
                var key, product, _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            key = id + "productById";
                            _a = basicCache.get(key);
                            if (_a) return [3 /*break*/, 2];
                            return [4 /*yield*/, fetch(baseUrl("products/" + id), { headers: headers })
                                    .then(function (res) { return res.json(); })
                                    .then(transformProduct)];
                        case 1:
                            _a = (_b.sent());
                            _b.label = 2;
                        case 2:
                            product = _a;
                            basicCache.set(key, product);
                            return [2 /*return*/, product];
                    }
                });
            });
        },
        getProductByHandle: function (handle) {
            return __awaiter(this, void 0, void 0, function () {
                var key, response, _a, product;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            key = handle + "productByHandle";
                            _a = basicCache.get(key);
                            if (_a) return [3 /*break*/, 2];
                            return [4 /*yield*/, fetch(baseUrl("products?where[active]=true&where[slug]=" + handle), {
                                    headers: headers,
                                }).then(function (res) { return res.json(); })];
                        case 1:
                            _a = (_b.sent());
                            _b.label = 2;
                        case 2:
                            response = _a;
                            basicCache.set(key, response);
                            product = response.results.map(transformProduct)[0];
                            return [2 /*return*/, product];
                    }
                });
            });
        },
        searchProducts: function (search) {
            return __awaiter(this, void 0, void 0, function () {
                var response;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, fetch(baseUrl("products?where[active]=true&search=" + search), {
                                headers: headers,
                            }).then(function (res) { return res.json(); })];
                        case 1:
                            response = _a.sent();
                            return [2 /*return*/, response.results.map(transformProduct)];
                    }
                });
            });
        },
        getRequestObject: function (id, resourceName) {
            return {
                '@type': '@builder.io/core:Request',
                request: {
                    url: baseUrl("products/" + id),
                },
                options: {
                    product: id,
                },
            };
        },
        getCollectionById: function (id) {
            return __awaiter(this, void 0, void 0, function () {
                var key, collection, _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            key = id + "collectionById";
                            _a = basicCache.get(key);
                            if (_a) return [3 /*break*/, 2];
                            return [4 /*yield*/, fetch(baseUrl("categories/" + id), { headers: headers })
                                    .then(function (res) { return res.json(); })
                                    .then(transformProduct)];
                        case 1:
                            _a = (_b.sent());
                            _b.label = 2;
                        case 2:
                            collection = _a;
                            basicCache.set(key, collection);
                            return [2 /*return*/, collection];
                    }
                });
            });
        },
        getCollectionByHandle: function (handle) {
            return __awaiter(this, void 0, void 0, function () {
                var key, response, _a, collection;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            key = handle + "collectionByHandle";
                            _a = basicCache.get(key);
                            if (_a) return [3 /*break*/, 2];
                            return [4 /*yield*/, fetch(baseUrl("categories?where[active]=true&where[slug]=" + handle), {
                                    headers: headers,
                                }).then(function (res) { return res.json(); })];
                        case 1:
                            _a = (_b.sent());
                            _b.label = 2;
                        case 2:
                            response = _a;
                            basicCache.set(key, response);
                            collection = response.results.map(transformProduct)[0];
                            return [2 /*return*/, collection];
                    }
                });
            });
        },
        searchCollections: function (search) {
            return __awaiter(this, void 0, void 0, function () {
                var response;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, fetch(baseUrl("categories?where[active]=true&search=" + search), {
                                headers: headers,
                            }).then(function (res) { return res.json(); })];
                        case 1:
                            response = _a.sent();
                            return [2 /*return*/, response.results.map(transformProduct)];
                    }
                });
            });
        },
    };
});
//# sourceMappingURL=swell.js.map