"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourcesPickerButton = exports.ResourcePicker = exports.ResourcePreviewCell = void 0;
const tslib_1 = require("tslib");
/** @jsx jsx */
const core_1 = require("@emotion/core");
const core_2 = require("@material-ui/core");
const icons_1 = require("@material-ui/icons");
const mobx_1 = require("mobx");
const mobx_react_1 = require("mobx-react");
const react_1 = require("react");
const set_keys_message_1 = require("../components/set-keys-message");
const pluralize_1 = require("pluralize");
const throttle_1 = require("lodash/throttle");
const ResourcePreviewCell = props => (0, mobx_react_1.useObserver)(() => ((0, core_1.jsx)(core_2.ListItem, { className: props.className, button: props.button, selected: props.selected },
    props.resource.image && ((0, core_1.jsx)(core_2.ListItemAvatar, null,
        (0, core_1.jsx)(core_2.Avatar, { css: { borderRadius: 4 }, src: props.resource.image.src }))),
    (0, core_1.jsx)(core_2.ListItemText, { primary: (0, core_1.jsx)("div", { css: {
                maxWidth: 400,
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
            } }, props.resource.title !== 'untitled' ? ((0, core_1.jsx)("div", null,
            props.resource.title,
            " - ",
            props.resource.id)) : (props.resource.title)) }))));
exports.ResourcePreviewCell = ResourcePreviewCell;
const ResourcePicker = props => {
    const store = (0, mobx_react_1.useLocalStore)(() => ({
        searchInputText: '',
        loading: false,
        resources: [],
        search: (0, throttle_1.default)(() => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
            store.loading = true;
            const catchError = (err) => {
                console.error('search error:', err);
                props.context.snackBar.show('Oh no! There was an error searching for resources');
            };
            const resourcesResponse = yield props.api[props.resourceName]
                .search(store.searchInputText)
                .catch(catchError);
            (0, mobx_1.runInAction)(() => {
                if (Array.isArray(resourcesResponse)) {
                    store.resources = resourcesResponse.filter(resource => !(props.omitIds || []).includes(String(resource.id)));
                }
                store.loading = false;
            });
        }), 400),
    }));
    (0, react_1.useEffect)(() => {
        store.search();
    }, [store.searchInputText]);
    return (0, mobx_react_1.useObserver)(() => ((0, core_1.jsx)("div", { css: { display: 'flex', flexDirection: 'column', minWidth: 500, padding: 30 } },
        (0, core_1.jsx)(core_2.TextField, { css: { marginBottom: 10 }, value: store.searchInputText, placeholder: props.title || `Search ${pluralize_1.default.plural(props.resourceName)}...`, InputProps: {
                style: {
                    padding: '8px 0px',
                },
                startAdornment: ((0, core_1.jsx)(core_2.InputAdornment, { css: { margin: '8px -2px 8px 8px' }, position: "start" },
                    (0, core_1.jsx)(icons_1.Search, { css: { color: 'var(--off-background-7)', fontSize: 20 } }))),
            }, onChange: (0, mobx_1.action)(e => (store.searchInputText = e.target.value)) }),
        store.loading && (0, core_1.jsx)(core_2.CircularProgress, { disableShrink: true, css: { margin: '50px auto' } }),
        (0, core_1.jsx)("div", null, !store.loading &&
            (store.resources.length ? (store.resources.map(item => {
                var _a;
                return ((0, core_1.jsx)("div", { key: item.id, onClick: e => {
                        props.onChange(item);
                    } },
                    (0, 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 })));
            })) : ((0, core_1.jsx)("div", null,
                (0, 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.ResourcePicker = ResourcePicker;
const ResourcesPickerButton = props => {
    const store = (0, mobx_react_1.useLocalStore)(() => {
        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),
            updateResourceId(newProps) {
                var _a, _b;
                this.resourceId = newProps.handleOnly
                    ? undefined
                    : typeof newProps.value === 'string'
                        ? newProps.value
                        : (_b = (_a = newProps.value) === null || _a === void 0 ? void 0 : _a.options) === null || _b === void 0 ? void 0 : _b.get(newProps.resourceName);
            },
            getResource() {
                return tslib_1.__awaiter(this, void 0, void 0, function* () {
                    this.error = null;
                    this.loading = true;
                    try {
                        const resourceService = props.api[props.resourceName];
                        const value = (this.resourceId && (yield resourceService.findById(this.resourceId))) ||
                            (this.resourceHandle &&
                                resourceService.findByHandle &&
                                (yield resourceService.findByHandle(this.resourceHandle)));
                        this.resourceInfo = value || null;
                    }
                    catch (e) {
                        console.error(e);
                        this.error = e;
                        props.context.snackBar.show(`Oh no! There was an error fetching ${pluralize_1.default.plural(props.resourceName)}`);
                    }
                    this.loading = false;
                });
            },
            showPickResouceModal(title) {
                return tslib_1.__awaiter(this, void 0, void 0, function* () {
                    const { value, resourcePicker } = props, rest = tslib_1.__rest(props, ["value", "resourcePicker"]);
                    const PickerCompnent = resourcePicker || exports.ResourcePicker;
                    const close = yield props.context.globalState.openDialog((0, core_1.jsx)(PickerCompnent, Object.assign({}, rest, { resourceName: props.resourceName }, (this.resourceInfo && { value: this.resourceInfo }), { title: title, onChange: (0, mobx_1.action)(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();
                        }) })), false, {
                        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',
                            },
                        },
                    });
                });
            },
        });
    });
    (0, react_1.useEffect)(() => {
        store.updateResourceId(props);
        store.getResource();
    }, [props.value]);
    (0, react_1.useEffect)(() => {
        var _a, _b;
        const hasPreviewFields = Boolean((_a = props.context.designerState.editingModel) === null || _a === void 0 ? void 0 : _a.fields.find((field) => 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(() => store.showPickResouceModal(`Pick a ${props.resourceName} to preview`));
        }
    }, [store.error]);
    return (0, mobx_react_1.useObserver)(() => {
        const pluginSettings = props.context.user.organization.value.settings.plugins.get(props.pluginId);
        if (!pluginSettings.get('hasConnected')) {
            return (0, core_1.jsx)(set_keys_message_1.SetEcomKeysMessage, { pluginId: props.pluginId, pluginName: props.pluginName });
        }
        return ((0, core_1.jsx)("div", { css: { display: 'flex', flexDirection: 'column', padding: '10px 0' } },
            store.loading && ((0, core_1.jsx)(core_2.CircularProgress, { size: 20, disableShrink: true, css: { margin: '30px auto' } })),
            store.resourceInfo && ((0, core_1.jsx)(core_2.Paper, { css: {
                    position: 'relative',
                } },
                (0, core_1.jsx)(exports.ResourcePreviewCell, { button: true, css: { paddingRight: 70 }, resource: store.resourceInfo }),
                (0, core_1.jsx)(core_2.IconButton, { css: {
                        position: 'absolute',
                        right: 42,
                        top: 0,
                        bottom: 0,
                        height: 50,
                        marginTop: 'auto',
                        marginBottom: 'auto',
                    }, onClick: () => {
                        store.showPickResouceModal();
                    } },
                    (0, core_1.jsx)(icons_1.Create, { css: { color: '#888' } })),
                (0, core_1.jsx)(core_2.IconButton, { css: {
                        position: 'absolute',
                        right: 2,
                        top: 0,
                        bottom: 0,
                        height: 50,
                        marginTop: 'auto',
                        marginBottom: 'auto',
                        opacity: 0.7,
                    }, onClick: (0, mobx_1.action)(() => {
                        store.resourceHandle = undefined;
                        store.resourceId = undefined;
                        store.resourceInfo = null;
                        props.onChange(undefined);
                    }) },
                    (0, core_1.jsx)(icons_1.Close, { css: { color: '#888' } })))),
            !store.resourceInfo && !store.loading && ((0, core_1.jsx)(core_2.Button, { color: "primary", variant: "contained", onClick: () => {
                    store.showPickResouceModal();
                } },
                "Choose ",
                props.resourceName))));
    });
};
exports.ResourcesPickerButton = ResourcesPickerButton;
//# sourceMappingURL=ResourcesPicker.js.map