"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 };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var jsx_runtime_1 = require("react/jsx-runtime");
var react_1 = require("react");
var lodash_1 = require("lodash");
var antd_1 = require("antd");
var mounted_1 = __importDefault(require("lib/hooks/mounted"));
var loading_1 = __importDefault(require("components/share/loading"));
var post_1 = __importDefault(require("lib/api/post"));
var icon_1 = require("@cocalc/frontend/components/icon");
var schema_1 = require("@cocalc/util/schema");
var misc_1 = require("@cocalc/util/misc");
var DEBOUNCE_MS = 1500;
function SaveButton(_a) {
    var _this = this;
    var disabled = _a.disabled, edited = _a.edited, original = _a.original, setOriginal = _a.setOriginal, table = _a.table, style = _a.style, onSave = _a.onSave, isValid = _a.isValid, debounce_ms = _a.debounce_ms;
    if (debounce_ms == null)
        debounce_ms = DEBOUNCE_MS;
    var _b = __read((0, react_1.useState)(false), 2), saving = _b[0], setSaving = _b[1];
    var _c = __read((0, react_1.useState)(""), 2), error = _c[0], setError = _c[1];
    // Tricky hooks: We have to store the state in a ref as well so that
    // we can use it in the save function, since that function
    // is memoized and called from a debounced function.
    var saveRef = (0, react_1.useRef)({ edited: edited, original: original, table: table });
    saveRef.current = { edited: edited, original: original, table: table };
    var isMounted = (0, mounted_1.default)();
    var save = (0, react_1.useMemo)(function () {
        return function () { return __awaiter(_this, void 0, void 0, function () {
            var _a, edited, original, table, changes, e, field, _b, _c, field, query, result, err_1;
            var e_1, _d, _e;
            return __generator(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        _a = saveRef.current, edited = _a.edited, original = _a.original, table = _a.table;
                        changes = false;
                        e = {};
                        for (field in edited) {
                            if (!(0, lodash_1.isEqual)(original[field], edited[field])) {
                                e[field] = (0, lodash_1.cloneDeep)(edited[field]);
                                changes = true;
                            }
                        }
                        if (!changes) {
                            // no changes to save.
                            return [2 /*return*/, false];
                        }
                        try {
                            for (_b = __values(preserveFields(table)), _c = _b.next(); !_c.done; _c = _b.next()) {
                                field = _c.value;
                                e[field] = (0, lodash_1.cloneDeep)(edited[field]);
                            }
                        }
                        catch (e_1_1) { e_1 = { error: e_1_1 }; }
                        finally {
                            try {
                                if (_c && !_c.done && (_d = _b.return)) _d.call(_b);
                            }
                            finally { if (e_1) throw e_1.error; }
                        }
                        query = (_e = {}, _e[table] = e, _e);
                        if (isMounted.current) {
                            setSaving(true);
                            setError("");
                        }
                        _f.label = 1;
                    case 1:
                        _f.trys.push([1, 3, 4, 5]);
                        return [4 /*yield*/, (0, post_1.default)("/user-query", { query: query })];
                    case 2:
                        // Note -- we definitely do want to do the save
                        // itself, even if the component is already unmounted,
                        // so we don't loose changes.
                        result = _f.sent();
                        return [3 /*break*/, 5];
                    case 3:
                        err_1 = _f.sent();
                        if (!isMounted.current)
                            return [2 /*return*/];
                        setError(err_1.message);
                        return [2 /*return*/, false];
                    case 4:
                        if (isMounted.current) {
                            setSaving(false);
                        }
                        return [7 /*endfinally*/];
                    case 5:
                        if (!isMounted.current)
                            return [2 /*return*/];
                        if (result.error) {
                            setError(result.error);
                        }
                        else {
                            setOriginal((0, lodash_1.cloneDeep)(edited));
                        }
                        return [2 /*return*/, true]; // successful save
                }
            });
        }); };
    }, []);
    function doSave() {
        return __awaiter(this, void 0, void 0, function () {
            var e, didSave, err_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        e = (0, lodash_1.cloneDeep)(saveRef.current.edited);
                        if (!table) return [3 /*break*/, 4];
                        return [4 /*yield*/, save()];
                    case 1:
                        didSave = _a.sent();
                        if (!isMounted.current)
                            return [2 /*return*/];
                        if (!didSave) return [3 /*break*/, 3];
                        return [4 /*yield*/, (onSave === null || onSave === void 0 ? void 0 : onSave(e))];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [2 /*return*/];
                    case 4:
                        _a.trys.push([4, 6, , 7]);
                        return [4 /*yield*/, (onSave === null || onSave === void 0 ? void 0 : onSave(e))];
                    case 5:
                        _a.sent();
                        if (!isMounted.current)
                            return [2 /*return*/];
                        setOriginal(e);
                        setError("");
                        return [3 /*break*/, 7];
                    case 6:
                        err_2 = _a.sent();
                        setError(err_2.toString());
                        return [3 /*break*/, 7];
                    case 7: return [2 /*return*/];
                }
            });
        });
    }
    var doSaveDebounced = (0, react_1.useMemo)(function () { return (0, lodash_1.debounce)(doSave, debounce_ms); }, [onSave]);
    (0, react_1.useEffect)(function () {
        doSaveDebounced();
        return doSaveDebounced;
    }, [edited]);
    var same = (0, lodash_1.isEqual)(edited, original);
    return ((0, jsx_runtime_1.jsxs)("div", __assign({ style: style }, { children: [(0, jsx_runtime_1.jsx)(antd_1.Button, __assign({ type: "primary", disabled: disabled !== null && disabled !== void 0 ? disabled : (saving || same || (isValid != null && !isValid(edited))), onClick: doSave }, { children: (0, jsx_runtime_1.jsxs)(antd_1.Space, { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "save" }), saving ? ((0, jsx_runtime_1.jsx)(loading_1.default, __assign({ delay: 250, before: "Save" }, { children: "Saving..." }))) : ("Save")] }) })), !same && error && ((0, jsx_runtime_1.jsx)(antd_1.Alert, { type: "error", message: error, style: { marginTop: "15px" } }))] })));
}
exports.default = SaveButton;
function preserveFields(table) {
    var _a, _b, _c;
    return (0, misc_1.keys)((_c = (_b = (_a = schema_1.SCHEMA[table].user_query) === null || _a === void 0 ? void 0 : _a.set) === null || _b === void 0 ? void 0 : _b.required_fields) !== null && _c !== void 0 ? _c : {});
}
//# sourceMappingURL=save-button.js.map