"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 });
/** @jsx jsx */
var core_1 = require("@emotion/core");
var core_2 = require("@material-ui/core");
var icons_1 = require("@material-ui/icons");
var mobx_1 = require("mobx");
var mobx_react_1 = require("mobx-react");
var react_1 = require("react");
var set_keys_message_1 = require("../components/set-keys-message");
var pluralize_1 = require("pluralize");
exports.ResourcePreviewCell = function (props) {
    return mobx_react_1.useObserver(function () { return (core_1.jsx(core_2.ListItem, { className: props.className, button: props.button, selected: props.selected },
        props.resource.image && (core_1.jsx(core_2.ListItemAvatar, null,
            core_1.jsx(core_2.Avatar, { css: { borderRadius: 4 }, src: props.resource.image.src }))),
        core_1.jsx(core_2.ListItemText, { primary: core_1.jsx("div", { css: {
                    maxWidth: 400,
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap',
                } }, props.resource.title) }))); });
};
exports.ResourcePicker = function (props) {
    var store = mobx_react_1.useLocalStore(function () { return ({
        searchInputText: '',
        loading: false,
        resources: [],
        search: function () {
            return __awaiter(this, void 0, void 0, function () {
                var catchError, resourcesResponse;
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.loading = true;
                            catchError = function (err) {
                                console.error('search error:', err);
                                props.context.snackBar.show('Oh no! There was an error searching for resources');
                            };
                            return [4 /*yield*/, props.api[props.resourceName]
                                    .search(store.searchInputText)
                                    .catch(catchError)];
                        case 1:
                            resourcesResponse = _a.sent();
                            mobx_1.runInAction(function () {
                                if (Array.isArray(resourcesResponse)) {
                                    _this.resources = resourcesResponse.filter(function (resource) { return !(props.omitIds || []).includes(String(resource.id)); });
                                }
                                _this.loading = false;
                            });
                            return [2 /*return*/];
                    }
                });
            });
        },
    }); });
    react_1.useEffect(function () {
        store.search();
    }, [store.searchInputText]);
    return mobx_react_1.useObserver(function () { return (core_1.jsx("div", { css: { display: 'flex', flexDirection: 'column', minWidth: 500 } },
        core_1.jsx(core_2.TextField, { css: { margin: 15 }, value: store.searchInputText, placeholder: props.title || "Search " + pluralize_1.default.plural(props.resourceName) + "...", InputProps: {
                startAdornment: (core_1.jsx(core_2.InputAdornment, { position: "start" },
                    core_1.jsx(icons_1.Search, { css: { color: '#999', marginRight: -2, fontSize: 20 } }))),
            }, onChange: mobx_1.action(function (e) { return (store.searchInputText = e.target.value); }) }),
        store.loading && core_1.jsx(core_2.CircularProgress, { disableShrink: true, css: { margin: '50px auto' } }),
        core_1.jsx("div", { css: { maxHeight: '80vh', overflow: 'auto' } }, !store.loading &&
            (store.resources.length ? (store.resources.map(function (item) {
                var _a;
                return (core_1.jsx("div", { key: item.id, onClick: function (e) {
                        props.onChange(item);
                    } },
                    core_1.jsx(exports.ResourcePreviewCell, { selected: String(item.id) === String((_a = props.value) === null || _a === void 0 ? void 0 : _a.id), button: true, resource: item, key: item.id })));
            })) : (core_1.jsx("div", null,
                core_1.jsx(core_2.Typography, { css: {
                        margin: '40px 20px',
                        textAlign: 'center',
                        fontSize: 17,
                    }, variant: "caption" },
                    "No ",
                    pluralize_1.default.plural(props.resourceName),
                    " found"))))))); });
};
exports.ResourcesPickerButton = function (props) {
    var store = mobx_react_1.useLocalStore(function () {
        var _a, _b;
        return ({
            loading: false,
            error: null,
            resourceInfo: null,
            resourceHandle: props.handleOnly && typeof props.value === 'string' ? props.value : undefined,
            resourceId: props.handleOnly
                ? undefined
                : typeof props.value === 'string'
                    ? props.value
                    : (_b = (_a = props.value) === null || _a === void 0 ? void 0 : _a.options) === null || _b === void 0 ? void 0 : _b.get(props.resourceName),
            getResource: function () {
                return __awaiter(this, void 0, void 0, function () {
                    var resourceService, value, _a, _b, _c, e_1;
                    return __generator(this, function (_d) {
                        switch (_d.label) {
                            case 0:
                                this.error = null;
                                this.loading = true;
                                _d.label = 1;
                            case 1:
                                _d.trys.push([1, 7, , 8]);
                                resourceService = props.api[props.resourceName];
                                _b = this.resourceId;
                                if (!_b) return [3 /*break*/, 3];
                                return [4 /*yield*/, resourceService.findById(this.resourceId)];
                            case 2:
                                _b = (_d.sent());
                                _d.label = 3;
                            case 3:
                                _a = (_b);
                                if (_a) return [3 /*break*/, 6];
                                _c = this.resourceHandle &&
                                    resourceService.findByHandle;
                                if (!_c) return [3 /*break*/, 5];
                                return [4 /*yield*/, resourceService.findByHandle(this.resourceHandle)];
                            case 4:
                                _c = (_d.sent());
                                _d.label = 5;
                            case 5:
                                _a = (_c);
                                _d.label = 6;
                            case 6:
                                value = _a;
                                this.resourceInfo = value || null;
                                return [3 /*break*/, 8];
                            case 7:
                                e_1 = _d.sent();
                                console.error(e_1);
                                this.error = e_1;
                                props.context.snackBar.show("Oh no! There was an error fetching " + pluralize_1.default.plural(props.resourceName));
                                return [3 /*break*/, 8];
                            case 8:
                                this.loading = false;
                                return [2 /*return*/];
                        }
                    });
                });
            },
            showPickResouceModal: function (title) {
                return __awaiter(this, void 0, void 0, function () {
                    var PickerCompnent, close;
                    var _this = this;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                PickerCompnent = props.resourcePicker ? props.resourcePicker : exports.ResourcePicker;
                                return [4 /*yield*/, props.context.globalState.openDialog(core_1.jsx(PickerCompnent, __assign({ resourceName: props.resourceName, api: props.api, context: props.context }, (this.resourceInfo && { value: this.resourceInfo }), { title: title, onChange: mobx_1.action(function (value) {
                                            var _a;
                                            if (value) {
                                                _this.resourceHandle = value.handle;
                                                _this.resourceId = String(value.id);
                                                _this.getResource();
                                                if (props.handleOnly) {
                                                    props.onChange(_this.resourceHandle);
                                                }
                                                else {
                                                    if ((_a = props.field) === null || _a === void 0 ? void 0 : _a.isTargeting) {
                                                        props.onChange(_this.resourceId);
                                                    }
                                                    else {
                                                        props.onChange(props.api[props.resourceName].getRequestObject(_this.resourceId, value));
                                                    }
                                                }
                                            }
                                            close();
                                        }) })), true, {
                                        PaperProps: {
                                            // Align modal to top so doesn't jump around centering itself when
                                            // grows and shrinks to show more/less resources or loading
                                            style: {
                                                alignSelf: 'flex-start',
                                            },
                                        },
                                    })];
                            case 1:
                                close = _a.sent();
                                return [2 /*return*/];
                        }
                    });
                });
            },
        });
    });
    react_1.useEffect(function () {
        store.getResource();
    }, []);
    react_1.useEffect(function () {
        var _a, _b;
        var hasPreviewFields = Boolean((_a = props.context.designerState.editingModel) === null || _a === void 0 ? void 0 : _a.fields.find(function (field) { return field.type === props.previewType; }));
        if (hasPreviewFields &&
            props.context.globalState.globalDialogs.length === 0 && ((_b = props.context.designerState) === null || _b === void 0 ? void 0 : _b.editingContentModel) &&
            props.isPreview &&
            (!props.value || store.error)) {
            setTimeout(function () { return store.showPickResouceModal("Pick a " + props.resourceName + " to preview"); });
        }
    }, [store.error]);
    return mobx_react_1.useObserver(function () {
        var pluginSettings = props.context.user.organization.value.settings.plugins.get(props.pluginId);
        if (!pluginSettings.get('hasConnected')) {
            return core_1.jsx(set_keys_message_1.SetEcomKeysMessage, { pluginId: props.pluginId, pluginName: props.pluginName });
        }
        return (core_1.jsx("div", { css: { display: 'flex', flexDirection: 'column', padding: '10px 0' } },
            store.loading && (core_1.jsx(core_2.CircularProgress, { size: 20, disableShrink: true, css: { margin: '30px auto' } })),
            store.resourceInfo && (core_1.jsx(core_2.Paper, { css: {
                    marginBottom: 15,
                    position: 'relative',
                } },
                core_1.jsx(exports.ResourcePreviewCell, { button: true, css: { paddingRight: 30 }, resource: store.resourceInfo }),
                core_1.jsx(core_2.IconButton, { css: {
                        position: 'absolute',
                        right: 2,
                        top: 0,
                        bottom: 0,
                        height: 50,
                        marginTop: 'auto',
                        marginBottom: 'auto',
                    }, onClick: function () {
                        store.showPickResouceModal();
                    } },
                    core_1.jsx(icons_1.Create, { css: { color: '#888' } })))),
            !store.resourceInfo && !store.loading && (core_1.jsx(core_2.Button, { color: "primary", variant: "contained", onClick: function () {
                    store.showPickResouceModal();
                } },
                "Choose ",
                props.resourceName))));
    });
};
//# sourceMappingURL=ResourcesPicker.js.map