"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");
/*
 *  This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
/*
Shopping cart.

The UX is similar to Amazon.com, since that's probably the single most popular
shopping cart experience, so most likely to feel familiar to users and easy
to use.
*/
var icon_1 = require("@cocalc/frontend/components/icon");
var describe_quota_1 = require("@cocalc/util/licenses/describe-quota");
var utils_1 = require("@cocalc/util/licenses/purchase/utils");
var misc_1 = require("@cocalc/util/misc");
var antd_1 = require("antd");
var A_1 = __importDefault(require("components/misc/A"));
var loading_1 = __importDefault(require("components/share/loading"));
var site_name_1 = __importDefault(require("components/share/site-name"));
var post_1 = __importDefault(require("lib/api/post"));
var api_1 = __importDefault(require("lib/hooks/api"));
var mounted_1 = __importDefault(require("lib/hooks/mounted"));
var router_1 = require("next/router");
var react_1 = require("react");
var other_items_1 = __importDefault(require("./other-items"));
var run_limit_1 = require("./run-limit");
var site_license_cost_1 = require("./site-license-cost");
function ShoppingCart() {
    var isMounted = (0, mounted_1.default)();
    var _a = __read((0, react_1.useState)(false), 2), updating = _a[0], setUpdating = _a[1];
    var _b = __read((0, react_1.useState)(0), 2), subTotal = _b[0], setSubTotal = _b[1];
    var router = (0, router_1.useRouter)();
    // most likely, user will checkout next
    (0, react_1.useEffect)(function () {
        router.prefetch("/store/checkout");
    }, []);
    var cart = (0, api_1.default)("/shopping/cart/get");
    var items = (0, react_1.useMemo)(function () {
        var e_1, _a;
        if (!cart.result)
            return undefined;
        // TODO deal with errors returned by useAPI
        if (cart.result.error != null)
            return undefined;
        var x = [];
        var subTotal = 0;
        try {
            for (var _b = __values(cart.result), _c = _b.next(); !_c.done; _c = _b.next()) {
                var item = _c.value;
                item.cost = (0, site_license_cost_1.computeCost)(item.description);
                if (item.checked) {
                    subTotal += item.cost.discounted_cost;
                }
                x.push(item);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
        setSubTotal(subTotal);
        return x;
    }, [cart.result]);
    if (cart.error) {
        return (0, jsx_runtime_1.jsx)(antd_1.Alert, { type: "error", message: cart.error });
    }
    if (!items) {
        return (0, jsx_runtime_1.jsx)(loading_1.default, { center: true });
    }
    function reload() {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!isMounted.current)
                            return [2 /*return*/];
                        setUpdating(true);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, , 3, 4]);
                        return [4 /*yield*/, cart.call()];
                    case 2:
                        _a.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        if (isMounted.current) {
                            setUpdating(false);
                        }
                        return [7 /*endfinally*/];
                    case 4: return [2 /*return*/];
                }
            });
        });
    }
    var columns = [
        {
            responsive: ["xs"],
            render: function (_a) {
                var id = _a.id, checked = _a.checked, cost = _a.cost, description = _a.description, type = _a.type;
                return ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(CheckboxColumn, __assign({}, { id: id, checked: checked, updating: updating, setUpdating: setUpdating, isMounted: isMounted, reload: reload })), (0, jsx_runtime_1.jsx)(DescriptionColumn, __assign({}, {
                            id: id,
                            cost: cost,
                            description: description,
                            updating: updating,
                            setUpdating: setUpdating,
                            isMounted: isMounted,
                            reload: reload,
                            type: type,
                        }, { compact: true })), (0, jsx_runtime_1.jsx)("div", { children: (0, jsx_runtime_1.jsx)("b", __assign({ style: { fontSize: "11pt" } }, { children: (0, jsx_runtime_1.jsx)(site_license_cost_1.DisplayCost, { cost: cost, simple: true, oneLine: true }) })) })] }));
            },
        },
        {
            responsive: ["sm"],
            title: "",
            render: function (_, _a) {
                var id = _a.id, checked = _a.checked;
                return ((0, jsx_runtime_1.jsx)(CheckboxColumn, __assign({}, { id: id, checked: checked, updating: updating, setUpdating: setUpdating, isMounted: isMounted, reload: reload })));
            },
        },
        {
            responsive: ["sm"],
            title: "Product",
            align: "center",
            render: function () { return ((0, jsx_runtime_1.jsxs)("div", __assign({ style: { color: "darkblue" } }, { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "key", style: { fontSize: "24px" } }), (0, jsx_runtime_1.jsx)("div", __assign({ style: { fontSize: "10pt" } }, { children: "Site License" }))] }))); },
        },
        {
            responsive: ["sm"],
            width: "60%",
            render: function (_, _a) {
                var id = _a.id, cost = _a.cost, description = _a.description, type = _a.type;
                return ((0, jsx_runtime_1.jsx)(DescriptionColumn, __assign({}, {
                    id: id,
                    cost: cost,
                    description: description,
                    updating: updating,
                    setUpdating: setUpdating,
                    isMounted: isMounted,
                    reload: reload,
                    type: type,
                }, { compact: false })));
            },
        },
        {
            responsive: ["sm"],
            title: "Price",
            align: "right",
            render: function (_, _a) {
                var cost = _a.cost;
                return ((0, jsx_runtime_1.jsx)("b", __assign({ style: { fontSize: "11pt" } }, { children: (0, jsx_runtime_1.jsx)(site_license_cost_1.DisplayCost, { cost: cost, simple: true }) })));
            },
        },
    ];
    function noItems() {
        return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsxs)("h3", { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "shopping-cart", style: { marginRight: "5px" } }), " Your", " ", (0, jsx_runtime_1.jsx)(site_name_1.default, {}), " Shopping Cart is Empty"] }), (0, jsx_runtime_1.jsx)(A_1.default, __assign({ href: "/store/site-license" }, { children: "Buy a License" }))] }));
    }
    function renderItems() {
        return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsxs)("div", __assign({ style: { float: "right", marginBottom: "15px" } }, { children: [(0, jsx_runtime_1.jsx)("span", __assign({ style: { fontSize: "13pt" } }, { children: (0, jsx_runtime_1.jsx)(TotalCost, { items: items }) })), (0, jsx_runtime_1.jsx)(A_1.default, __assign({ href: "/store/checkout" }, { children: (0, jsx_runtime_1.jsx)(antd_1.Button, __assign({ disabled: subTotal == 0 || updating, style: { marginLeft: "15px" }, size: "large", type: "primary" }, { children: "Proceed to Checkout" })) }))] })), (0, jsx_runtime_1.jsxs)("h3", { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "shopping-cart", style: { marginRight: "5px" } }), " ", "Shopping Cart"] }), (0, jsx_runtime_1.jsx)("div", __assign({ style: { marginTop: "-10px", marginBottom: "5px" } }, { children: (0, jsx_runtime_1.jsx)(SelectAllItems, { items: items, onChange: reload }) })), (0, jsx_runtime_1.jsx)("div", __assign({ style: { border: "1px solid #eee" } }, { children: (0, jsx_runtime_1.jsx)(antd_1.Table, { showHeader: false, columns: columns, dataSource: items, rowKey: "id", pagination: { hideOnSinglePage: true } }) })), (0, jsx_runtime_1.jsxs)("div", __assign({ style: {
                        float: "right",
                        fontSize: "12pt",
                        margin: "15px 15px 0 0",
                    } }, { children: [(0, jsx_runtime_1.jsx)("div", __assign({ style: { float: "right" } }, { children: (0, jsx_runtime_1.jsx)(TotalCost, { items: cart.result }) })), (0, jsx_runtime_1.jsx)("br", {})] }))] }));
    }
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [items.length == 0 && noItems(), items.length > 0 && renderItems(), (0, jsx_runtime_1.jsx)("div", __assign({ style: {
                    marginTop: "60px",
                    border: "1px solid #eee",
                } }, { children: (0, jsx_runtime_1.jsx)(other_items_1.default, { onChange: reload, cart: cart }) }))] }));
}
exports.default = ShoppingCart;
function TotalCost(_a) {
    var e_2, _b;
    var items = _a.items;
    var discounted_cost = 0;
    var n = 0;
    try {
        for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
            var _c = items_1_1.value, cost = _c.cost, checked = _c.checked;
            if (checked) {
                discounted_cost += cost.discounted_cost;
                n += 1;
            }
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (items_1_1 && !items_1_1.done && (_b = items_1.return)) _b.call(items_1);
        }
        finally { if (e_2) throw e_2.error; }
    }
    if (n == 0) {
        return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: "No items selected" });
    }
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: ["Subtotal (", n, " items): ", (0, jsx_runtime_1.jsx)("b", { children: (0, utils_1.money)(discounted_cost) })] }));
}
function SelectAllItems(_a) {
    var items = _a.items, onChange = _a.onChange;
    var numSelected = (0, react_1.useMemo)(function () {
        var e_3, _a;
        var n = 0;
        if (items == null)
            return n;
        try {
            for (var items_2 = __values(items), items_2_1 = items_2.next(); !items_2_1.done; items_2_1 = items_2.next()) {
                var item = items_2_1.value;
                if (item.checked)
                    n += 1;
            }
        }
        catch (e_3_1) { e_3 = { error: e_3_1 }; }
        finally {
            try {
                if (items_2_1 && !items_2_1.done && (_a = items_2.return)) _a.call(items_2);
            }
            finally { if (e_3) throw e_3.error; }
        }
        return n;
    }, [items]);
    if (items == null)
        return null;
    function doSelectAll(checked) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, (0, post_1.default)("/shopping/cart/checked", { checked: checked })];
                    case 1:
                        _a.sent();
                        onChange();
                        return [2 /*return*/];
                }
            });
        });
    }
    if (numSelected == 0) {
        return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: ["No items selected.", " ", (0, jsx_runtime_1.jsx)("a", __assign({ onClick: function () { return doSelectAll(true); } }, { children: "Select all items" }))] }));
    }
    if (numSelected < items.length) {
        return (0, jsx_runtime_1.jsx)("a", __assign({ onClick: function () { return doSelectAll(true); } }, { children: "Select all items" }));
    }
    return (0, jsx_runtime_1.jsx)("a", __assign({ onClick: function () { return doSelectAll(false); } }, { children: "Deselect all items" }));
}
function CheckboxColumn(_a) {
    var _this = this;
    var id = _a.id, checked = _a.checked, updating = _a.updating, setUpdating = _a.setUpdating, isMounted = _a.isMounted, reload = _a.reload;
    return ((0, jsx_runtime_1.jsx)(antd_1.Checkbox, __assign({ disabled: updating, checked: checked, onChange: function (e) { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        setUpdating(true);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, , 4, 5]);
                        return [4 /*yield*/, (0, post_1.default)("/shopping/cart/checked", {
                                id: id,
                                checked: e.target.checked,
                            })];
                    case 2:
                        _a.sent();
                        if (!isMounted.current)
                            return [2 /*return*/];
                        return [4 /*yield*/, reload()];
                    case 3:
                        _a.sent();
                        return [3 /*break*/, 5];
                    case 4:
                        if (!isMounted.current)
                            return [2 /*return*/];
                        setUpdating(false);
                        return [7 /*endfinally*/];
                    case 5: return [2 /*return*/];
                }
            });
        }); } }, { children: (0, jsx_runtime_1.jsx)("span", __assign({ className: "sr-only" }, { children: "Select" })) })));
}
function DescriptionColumn(props) {
    var _this = this;
    var id = props.id, cost = props.cost, description = props.description, updating = props.updating, setUpdating = props.setUpdating, isMounted = props.isMounted, reload = props.reload, compact = props.compact;
    var router = (0, router_1.useRouter)();
    var input = cost.input;
    var _a = __read((0, react_1.useState)(false), 2), editRunLimit = _a[0], setEditRunLimit = _a[1];
    var _b = __read((0, react_1.useState)(description.run_limit), 2), runLimit = _b[0], setRunLimit = _b[1];
    var showRunLimitEditor = description.type !== "disk" && description.type !== "vm";
    function editableQuota() {
        var _this = this;
        return ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsxs)("div", { children: [(0, describe_quota_1.describeQuotaFromInfo)(input), showRunLimitEditor && !editRunLimit && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsxs)(antd_1.Button, __assign({ onClick: function () { return setEditRunLimit(true); }, disabled: updating, style: { marginBottom: "5px" } }, { children: [runLimit, " simultaneous running ", (0, misc_1.plural)(runLimit, "project")] }))] }))] }), (0, jsx_runtime_1.jsx)("div", { children: editRunLimit && ((0, jsx_runtime_1.jsxs)("div", __assign({ style: {
                            border: "1px solid #eee",
                            padding: "15px",
                            margin: "15px 0",
                            background: "white",
                        } }, { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "times", style: { float: "right" }, onClick: function () {
                                    setEditRunLimit(false);
                                } }), (0, jsx_runtime_1.jsx)(run_limit_1.EditRunLimit, { value: runLimit, onChange: setRunLimit }), (0, jsx_runtime_1.jsx)(antd_1.Button, __assign({ type: "primary", style: { marginTop: "15px" }, onClick: function () { return __awaiter(_this, void 0, void 0, function () {
                                    return __generator(this, function (_a) {
                                        switch (_a.label) {
                                            case 0:
                                                setEditRunLimit(false);
                                                return [4 /*yield*/, (0, post_1.default)("/shopping/cart/edit", {
                                                        id: id,
                                                        description: __assign(__assign({}, description), { run_limit: runLimit }),
                                                    })];
                                            case 1:
                                                _a.sent();
                                                return [4 /*yield*/, reload()];
                                            case 2:
                                                _a.sent();
                                                return [2 /*return*/];
                                        }
                                    });
                                }); } }, { children: "Save" }))] }))) })] }));
    }
    // this could rely an the "type" field, but we rather check the data directly
    function editPage() {
        if (input.type === "disk" || input.type === "vm") {
            return "dedicated";
        }
        else if (input.boost) {
            return "boost";
        }
        return "site-license";
    }
    return ((0, jsx_runtime_1.jsxs)("div", __assign({ style: { fontSize: "12pt" } }, { children: [description.title && ((0, jsx_runtime_1.jsx)("div", { children: (0, jsx_runtime_1.jsx)("b", { children: description.title }) })), description.description && (0, jsx_runtime_1.jsx)("div", { children: description.description }), (0, jsx_runtime_1.jsx)("div", { children: (0, jsx_runtime_1.jsx)("b", { children: input.subscription == "no"
                        ? (0, site_license_cost_1.describePeriod)(input)
                        : (0, misc_1.capitalize)(input.subscription) + " subscription" }) }), (0, jsx_runtime_1.jsxs)("div", __assign({ style: {
                    border: "1px solid lightblue",
                    background: "white",
                    padding: "15px 15px 5px 15px",
                    margin: "5px 0 10px 0",
                    borderRadius: "5px",
                } }, { children: [compact ? (0, site_license_cost_1.describeItem)(input) : editableQuota(), " "] })), (0, jsx_runtime_1.jsxs)(antd_1.Button, __assign({ style: { marginRight: "5px" }, onClick: function () {
                    var page = editPage();
                    router.push("/store/".concat(page, "?id=").concat(id));
                } }, { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "pencil" }), " Edit"] })), (0, jsx_runtime_1.jsxs)(antd_1.Button, __assign({ style: { margin: "0 5px 5px 0" }, disabled: updating, onClick: function () { return __awaiter(_this, void 0, void 0, function () {
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                setUpdating(true);
                                _a.label = 1;
                            case 1:
                                _a.trys.push([1, , 4, 5]);
                                return [4 /*yield*/, (0, post_1.default)("/shopping/cart/remove", { id: id })];
                            case 2:
                                _a.sent();
                                if (!isMounted.current)
                                    return [2 /*return*/];
                                return [4 /*yield*/, reload()];
                            case 3:
                                _a.sent();
                                return [3 /*break*/, 5];
                            case 4:
                                if (!isMounted.current)
                                    return [2 /*return*/];
                                setUpdating(false);
                                return [7 /*endfinally*/];
                            case 5: return [2 /*return*/];
                        }
                    });
                }); } }, { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "save" }), " Save for later"] })), (0, jsx_runtime_1.jsx)(antd_1.Popconfirm, __assign({ title: "Are you sure you want to delete this item?", onConfirm: function () { return __awaiter(_this, void 0, void 0, function () {
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                setUpdating(true);
                                _a.label = 1;
                            case 1:
                                _a.trys.push([1, , 4, 5]);
                                return [4 /*yield*/, (0, post_1.default)("/shopping/cart/delete", { id: id })];
                            case 2:
                                _a.sent();
                                if (!isMounted.current)
                                    return [2 /*return*/];
                                return [4 /*yield*/, reload()];
                            case 3:
                                _a.sent();
                                return [3 /*break*/, 5];
                            case 4:
                                if (!isMounted.current)
                                    return [2 /*return*/];
                                setUpdating(false);
                                return [7 /*endfinally*/];
                            case 5: return [2 /*return*/];
                        }
                    });
                }); }, okText: "Yes, delete this item", cancelText: "Cancel" }, { children: (0, jsx_runtime_1.jsxs)(antd_1.Button, __assign({ disabled: updating, type: "dashed" }, { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "trash" }), " Delete"] })) }))] })));
}
//# sourceMappingURL=cart.js.map