"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 __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
 */
/*
Create a new site license.
*/
var icon_1 = require("@cocalc/frontend/components/icon");
var local_storage_1 = require("@cocalc/frontend/misc/local-storage");
var dedicated_1 = require("@cocalc/util/consts/dedicated");
var project_1 = require("@cocalc/util/consts/project");
var check_disk_name_basics_1 = require("@cocalc/util/licenses/check-disk-name-basics");
var utils_1 = require("@cocalc/util/licenses/purchase/utils");
var dedicated_2 = require("@cocalc/util/types/dedicated");
var dedicated_3 = require("@cocalc/util/upgrades/dedicated");
var antd_1 = require("antd");
var A_1 = __importDefault(require("components/misc/A"));
var integer_slider_1 = __importDefault(require("components/misc/integer-slider"));
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 use_scroll_y_1 = require("lib/use-scroll-y");
var lodash_1 = require("lodash");
var router_1 = require("next/router");
var react_1 = require("react");
var add_box_1 = require("./add-box");
var apply_license_to_project_1 = require("./apply-license-to-project");
var compute_cost_1 = require("./compute-cost");
var cost_info_bar_1 = require("./cost-info-bar");
var sign_in_to_purchase_1 = require("./sign-in-to-purchase");
var title_description_1 = require("./title-description");
var toggle_explanations_1 = require("./toggle-explanations");
var usage_and_duration_1 = require("./usage-and-duration");
var util_1 = require("./util");
var Text = antd_1.Typography.Text;
var GCP_DISK_URL = "https://cloud.google.com/compute/docs/disks/performance#performance_by_disk_size";
function DedicatedResource(props) {
    var noAccount = props.noAccount;
    var router = (0, router_1.useRouter)();
    var headerRef = (0, react_1.useRef)(null);
    // most likely, user will go to the cart next
    (0, react_1.useEffect)(function () {
        router.prefetch("/store/cart");
    }, []);
    var _a = __read((0, react_1.useState)(0), 2), offsetHeader = _a[0], setOffsetHeader = _a[1];
    var scrollY = (0, use_scroll_y_1.useScrollY)();
    (0, react_1.useEffect)(function () {
        if (headerRef.current) {
            setOffsetHeader(headerRef.current.offsetTop);
        }
    }, []);
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsxs)("h3", __assign({ ref: headerRef }, { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "dedicated", style: { marginRight: "5px" } }), " ", router.query.id != null
                        ? "Edit Dedicated Resources License in Shopping Cart"
                        : "Buy a Dedicated Resources License"] })), router.query.id == null && ((0, jsx_runtime_1.jsxs)("p", { children: ["A", " ", (0, jsx_runtime_1.jsxs)(A_1.default, __assign({ href: "https://doc.cocalc.com/licenses.html" }, { children: [(0, jsx_runtime_1.jsx)(site_name_1.default, {}), " dedicated resource license"] })), " ", "can be used to outfit your project either with additional disk storage or moves your project to a much more powerful virtual machine. Create a dedicated resources license below then add it to your", " ", (0, jsx_runtime_1.jsx)(A_1.default, __assign({ href: "/store/cart" }, { children: "shopping cart" })), "."] })), (0, jsx_runtime_1.jsx)(CreateDedicatedResource, { showInfoBar: scrollY > offsetHeader, noAccount: noAccount })] }));
}
exports.default = DedicatedResource;
function CreateDedicatedResource(_a) {
    var _this = this;
    var _b = _a.showInfoBar, showInfoBar = _b === void 0 ? false : _b, _c = _a.noAccount, noAccount = _c === void 0 ? false : _c;
    // somehow this state is necessary to render the form properly
    var _d = __read((0, react_1.useState)(null), 2), formType = _d[0], setFormType = _d[1];
    var _e = __read((0, react_1.useState)(undefined), 2), cost = _e[0], setCost = _e[1];
    var _f = __read((0, react_1.useState)(false), 2), loading = _f[0], setLoading = _f[1];
    var _g = __read((0, react_1.useState)(""), 2), cartError = _g[0], setCartError = _g[1];
    var _h = __read((0, react_1.useState)(true), 2), showExplanations = _h[0], setShowExplanations = _h[1];
    var _j = __read((0, react_1.useState)("monthly"), 2), durationTypes = _j[0], setDdurationTypes = _j[1];
    var _k = __read((0, react_1.useState)(null), 2), vmMachine = _k[0], setVmMachine = _k[1];
    var _l = __read((0, react_1.useState)(false), 2), diskNameValid = _l[0], setDiskNameValid = _l[1];
    var _m = __read((0, react_1.useState)(false), 2), showInfo = _m[0], setShowInfo = _m[1];
    var _o = __read(antd_1.Form.useForm(), 1), form = _o[0];
    var router = (0, router_1.useRouter)();
    // most likely, user will go to the cart next
    (0, react_1.useEffect)(function () {
        router.prefetch("/store/cart");
    }, []);
    function fixupDuration() {
        switch (form.getFieldValue("type")) {
            case "disk":
                setDdurationTypes("monthly");
                if (form.getFieldValue("period") === "range") {
                    form.setFieldsValue({ period: "monthly" });
                }
                break;
            case "vm":
                setDdurationTypes("range");
                if (form.getFieldValue("period") !== "range") {
                    form.setFieldsValue({ period: "range" });
                }
                break;
        }
    }
    function calcCost() {
        var data = form.getFieldsValue(true);
        try {
            switch (data.type) {
                case "disk":
                    var size_gb = data["disk-size_gb"];
                    var speed = data["disk-speed"];
                    if (size_gb == null || speed == null) {
                        return; // no data to compute price
                    }
                    setCost((0, compute_cost_1.computeCost)({
                        type: "disk",
                        period: "monthly",
                        dedicated_disk: {
                            speed: speed,
                            size_gb: size_gb,
                            name: data["disk-name"],
                        },
                    }));
                    break;
                case "vm":
                    setCost((0, compute_cost_1.computeCost)({
                        type: "vm",
                        period: "range",
                        range: data.range,
                        dedicated_vm: {
                            machine: data["vm-machine"],
                        },
                    }));
                    break;
            }
        }
        catch (err) {
            console.log("error computing cost: ".concat(err));
            setCost(undefined);
        }
    }
    function onChange() {
        fixupDuration();
        calcCost();
    }
    function loadItem(item) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var type, conf, _b, d, err_1, vm;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (item.product !== "site-license") {
                            throw new Error("not a site license");
                        }
                        type = (0, util_1.getType)(item);
                        if (type !== "disk" && type !== "vm") {
                            throw new Error("cannot deal with type ".concat(type));
                        }
                        conf = item.description;
                        // restoring name/description
                        form.setFieldsValue({
                            title: conf.title,
                            description: conf.description,
                        });
                        _b = type;
                        switch (_b) {
                            case "disk": return [3 /*break*/, 1];
                            case "vm": return [3 /*break*/, 6];
                        }
                        return [3 /*break*/, 7];
                    case 1:
                        d = conf.dedicated_disk;
                        form.setFieldsValue({
                            type: type,
                            "disk-size_gb": d.size_gb,
                            "disk-speed": d.type,
                            "disk-name": d.name,
                        });
                        _c.label = 2;
                    case 2:
                        _c.trys.push([2, 4, , 5]);
                        return [4 /*yield*/, testDedicatedDiskName(d.name)];
                    case 3:
                        _c.sent();
                        setDiskNameValid(true);
                        return [3 /*break*/, 5];
                    case 4:
                        err_1 = _c.sent();
                        setDiskNameValid(false);
                        return [3 /*break*/, 5];
                    case 5: return [3 /*break*/, 7];
                    case 6:
                        vm = (_a = conf.dedicated_vm) === null || _a === void 0 ? void 0 : _a.machine;
                        if (dedicated_3.PRICES.vms[vm] == null) {
                            console.warn("VM type ".concat(vm, " not found"));
                        }
                        else {
                            form.setFieldsValue({
                                "vm-machine": vm,
                            });
                        }
                        form.setFieldsValue({
                            type: type,
                            range: (0, util_1.loadDateRange)(conf.range),
                        });
                        return [3 /*break*/, 7];
                    case 7:
                        // unpacking and configuring the form worked, now we do the type selection to show it
                        setFormType(type);
                        return [2 /*return*/];
                }
            });
        });
    }
    (0, react_1.useEffect)(function () {
        var store_site_license_show_explanations = (0, local_storage_1.get_local_storage)("store_site_license_show_explanations");
        if (store_site_license_show_explanations != null) {
            setShowExplanations(!!store_site_license_show_explanations);
        }
        var id = router.query.id;
        if (!noAccount && id != null) {
            // editing something in the shopping cart
            (function () { return __awaiter(_this, void 0, void 0, function () {
                var item, err_2;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 3, 4, 5]);
                            setLoading(true);
                            return [4 /*yield*/, (0, post_1.default)("/shopping/cart/get", { id: id })];
                        case 1:
                            item = _a.sent();
                            return [4 /*yield*/, loadItem(item)];
                        case 2:
                            _a.sent();
                            return [3 /*break*/, 5];
                        case 3:
                            err_2 = _a.sent();
                            setCartError(err_2.message);
                            return [3 /*break*/, 5];
                        case 4:
                            setLoading(false);
                            return [7 /*endfinally*/];
                        case 5:
                            onChange();
                            return [2 /*return*/];
                    }
                });
            }); })();
        }
        onChange();
    }, []);
    (0, react_1.useEffect)(function () {
        var type = router.query.type;
        if (typeof type === "string") {
            setType(type);
        }
    }, []);
    (0, react_1.useEffect)(function () {
        form.validateFields();
    }, [form.getFieldValue("type")]);
    if (loading) {
        return (0, jsx_runtime_1.jsx)(loading_1.default, { large: true, center: true });
    }
    function setType(type) {
        if (type === "vm" || type === "disk") {
            form.resetFields();
            form.setFieldsValue({ type: type });
            setFormType(type);
            setCost(undefined);
            setCartError("");
            onChange();
        }
        else {
            console.log("unable to setType to ".concat(type));
        }
    }
    function renderTypeSelection() {
        return ((0, jsx_runtime_1.jsx)(antd_1.Form.Item, __assign({ name: "type", label: "Dedicated", rules: [{ required: true, message: "Please select a type" }], extra: showExplanations && ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: "Select if you want to get a Dedicate Disk or a Virtual Machine." })) }, { children: (0, jsx_runtime_1.jsxs)(antd_1.Radio.Group, __assign({ onChange: function (e) {
                    setType(e.target.value);
                } }, { children: [(0, jsx_runtime_1.jsx)(antd_1.Radio.Button, __assign({ value: "disk" }, { children: "Disk" }), "disk"), (0, jsx_runtime_1.jsx)(antd_1.Radio.Button, __assign({ value: "vm" }, { children: "Virtual Machine" }), "vm")] })) })));
    }
    function renderAdditionalInfoContent() {
        switch (formType) {
            case "disk":
                return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsxs)(antd_1.Typography.Paragraph, __assign({ ellipsis: {
                                expandable: true,
                                rows: 2,
                                symbol: "more",
                                onExpand: function () { return setShowInfo(true); },
                            } }, { children: ["This license attaches a disk to your project. When the license is valid and activated by adding to a project, a disk will be created on the fly. It will be formatted and mounted into your project. You'll be able to access it via a symlink in your project's home directory \u2013 i.e. ", (0, jsx_runtime_1.jsxs)("code", { children: ["~/", dedicated_1.HOME_PREFIX, "/<name>"] }), " will be pointing to ", (0, jsx_runtime_1.jsxs)("code", { children: [dedicated_1.ROOT, "/<name>"] }), "."] })), (0, jsx_runtime_1.jsxs)(antd_1.Typography.Paragraph, __assign({ style: { display: showInfo ? "" : "none" } }, { children: ["Once you cancel the subscription, the subscription will end at the end of the billing period. Then, the disk and all the data it contains ", (0, jsx_runtime_1.jsx)("strong", { children: "will be deleted" }), "!"] })), (0, jsx_runtime_1.jsx)(antd_1.Typography.Paragraph, __assign({ style: { display: showInfo ? "" : "none" } }, { children: "It's also possible to move a disk from one project to another one. First, remove the license from the project, restart the project to unmount the disk. Then, add the license to another project and restart that project as well." })), (0, jsx_runtime_1.jsxs)(antd_1.Typography.Paragraph, __assign({ style: { display: showInfo ? "" : "none" } }, { children: ["Note: it is also possible to mount external data storage to a project:", " ", (0, jsx_runtime_1.jsx)(A_1.default, __assign({ href: project_1.DOC_CLOUD_STORAGE_URL }, { children: "cloud storage & remote file systems" })), ". This could help transferring data in and out of ", (0, jsx_runtime_1.jsx)(site_name_1.default, {}), "."] }))] }));
            case "vm":
                return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsxs)(antd_1.Typography.Paragraph, __assign({ ellipsis: {
                                expandable: true,
                                rows: 2,
                                symbol: "more",
                                onExpand: function () { return setShowInfo(true); },
                            } }, { children: ["For the specified period of time, a virtual machine is provisioned and started inside of ", (0, jsx_runtime_1.jsx)(site_name_1.default, {}), "'s cluster. You have to add the license to one of your projects in order to tell it to move to this virtual machine. This happens when the project is started or restarted."] })), (0, jsx_runtime_1.jsx)(antd_1.Typography.Paragraph, __assign({ style: { display: showInfo ? "" : "none" } }, { children: "Once your project has moved over, the usual quota upgrades will be ineffective \u2013 instead, your project runs with the quota limits implied by the performance of the underlying virtual machine. The files/data in your project will be exactly the same as before." })), (0, jsx_runtime_1.jsx)(antd_1.Typography.Paragraph, __assign({ style: { display: showInfo ? "" : "none" } }, { children: "Once the license period is over, the virtual machine will be shut down. At that point your project will be stopped as well. The next time it starts, it will run under the usual quota regime on a shared node in the cluster." }))] }));
        }
    }
    function renderAdditionalInfo() {
        return ((0, jsx_runtime_1.jsx)(antd_1.Form.Item, __assign({ label: "How does it work?" }, { children: (0, jsx_runtime_1.jsx)("div", __assign({ style: { paddingTop: "5px" } }, { children: renderAdditionalInfoContent() })) })));
    }
    function renderDurationExplanation() {
        if (!showExplanations)
            return;
        switch (durationTypes) {
            case "monthly":
                return ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: "Currently, disk can be only be rented on a monthly basis only. Note: you can cancel the subscription any time and at the end of the billing period the disk \u2013 and the data it holds \u2013 will be destroyed." }));
            case "range":
                return ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: "Dedicated VMs can only be rented for a specific period of time. At its end, the node will be stopped and removed, and your project moves back to the usual upgrade schema." }));
        }
    }
    function renderUsageAndDuration() {
        return ((0, jsx_runtime_1.jsx)(usage_and_duration_1.UsageAndDuration, { extraDuration: renderDurationExplanation(), form: form, onChange: onChange, showUsage: false, duration: durationTypes, discount: false }));
    }
    function testDedicatedDiskName(name) {
        return __awaiter(this, void 0, void 0, function () {
            var serverCheck;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        (0, check_disk_name_basics_1.testDedicatedDiskNameBasic)(name);
                        return [4 /*yield*/, (0, post_1.default)("licenses/check-disk-name", { name: name }, 60)];
                    case 1:
                        serverCheck = _a.sent();
                        if ((serverCheck === null || serverCheck === void 0 ? void 0 : serverCheck.available) === true) {
                            return [2 /*return*/];
                        }
                        else {
                            throw new Error("Please choose a different disk name.");
                        }
                        return [2 /*return*/];
                }
            });
        });
    }
    /**
     * The disk name will get a prefix like "kucalc-[cluster id]-pd-[namespace]-dedicated-..."
     * It's impossible to know the prefix, since the properties of the cluster can change.
     * The maximum total length of the disk name is 63, according to the GCE documentation.
     * https://cloud.google.com/compute/docs/naming-resources#resource-name-format
     * I hope a max length of 20 is sufficiently restrictive.
     */
    function validateDedicatedDiskName() {
        var _this = this;
        return {
            validator: function (_, name) { return __awaiter(_this, void 0, void 0, function () {
                var err_3;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            return [4 /*yield*/, testDedicatedDiskName(name)];
                        case 1:
                            _a.sent();
                            setDiskNameValid(true);
                            return [2 /*return*/, Promise.resolve()];
                        case 2:
                            err_3 = _a.sent();
                            setDiskNameValid(false);
                            return [2 /*return*/, Promise.reject(err_3.message)];
                        case 3: return [2 /*return*/];
                    }
                });
            }); },
        };
    }
    function renderDedicatedDiskInfo() {
        if (!showExplanations)
            return;
        return ((0, jsx_runtime_1.jsxs)("p", { children: ["More information about Dedicated Disks can be found at", " ", (0, jsx_runtime_1.jsx)(A_1.default, __assign({ href: GCP_DISK_URL }, { children: "GCP: Performance by disk size" })), "."] }));
    }
    function renderDiskPerformance() {
        var size_gb = form.getFieldValue("disk-size_gb");
        var speed = form.getFieldValue("disk-speed");
        if (size_gb == null || speed == null)
            return;
        var diskID = (0, dedicated_3.getDedicatedDiskKey)({ size_gb: size_gb, speed: speed });
        var di = dedicated_3.PRICES.disks[diskID];
        if (di == null) {
            return ((0, jsx_runtime_1.jsxs)("p", __assign({ style: { marginTop: "5px" } }, { children: ["Unknown disk with ID ", (0, jsx_runtime_1.jsx)("code", { children: diskID }), "."] })));
        }
        return ((0, jsx_runtime_1.jsxs)("p", __assign({ style: { marginTop: "5px" } }, { children: ["Estimated speed: ", di.mbps, " MB/s sustained throughput and ", di.iops, " IOPS read/write. For more detailed information:", " ", (0, jsx_runtime_1.jsx)(A_1.default, __assign({ href: GCP_DISK_URL }, { children: "GCP disk performance" })), " information."] })));
    }
    function renderDiskExtra() {
        if (!showExplanations)
            return;
        var formName = form.getFieldValue("disk-name");
        var name = formName ? formName : (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: "<name>" });
        return ((0, jsx_runtime_1.jsxs)("p", { children: ["Give your disk a name. It must be unique and will be used as part of the directory name. The mount point will be", " ", (0, jsx_runtime_1.jsxs)("code", { children: [dedicated_1.ROOT, "/", name] }), " ", "and if the name isn't already taken. For your convenience, if possible there will be a symlink named", " ", (0, jsx_runtime_1.jsxs)("code", { children: ["~/", dedicated_1.HOME_PREFIX, "/", name] }), " ", "pointing from your home directory to your disk for your convenience."] }));
    }
    // ATTN: the IntegerSlider must be kept in sync with DEDICATED_DISK_SIZES in
    // src/packages/util/upgrades/dedicated.ts
    function renderDedicatedDisk() {
        return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(antd_1.Form.Item, __assign({ name: "disk-name", label: "Name", hasFeedback: true, extra: renderDiskExtra(), rules: [validateDedicatedDiskName] }, { children: (0, jsx_runtime_1.jsx)(antd_1.Input, { style: { width: "15em" } }) })), (0, jsx_runtime_1.jsx)(antd_1.Form.Item, __assign({ label: "Size", name: "disk-size_gb", initialValue: dedicated_3.DEFAULT_DEDICATED_DISK_SIZE, extra: showExplanations && (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: "Select the size of the dedicated disk." }) }, { children: (0, jsx_runtime_1.jsx)(integer_slider_1.default, { min: dedicated_3.MIN_DEDICATED_DISK_SIZE, max: dedicated_3.MAX_DEDICATED_DISK_SIZE, step: dedicated_3.DEDICATED_DISK_SIZE_INCREMENT, onChange: function (val) {
                            form.setFieldsValue({ "disk-size_gb": val });
                            onChange();
                        }, units: "G", presets: [32, 64, 128, 256, 512, 1024] }) })), (0, jsx_runtime_1.jsx)(antd_1.Form.Item, __assign({ name: "disk-speed", label: "Speed", initialValue: dedicated_3.DEFAULT_DEDICATED_DISK_SPEED, extra: renderDedicatedDiskInfo() }, { children: (0, jsx_runtime_1.jsx)(antd_1.Radio.Group, __assign({ onChange: function (e) {
                            form.setFieldsValue({ "disk-speed": e.target.value });
                            onChange();
                        } }, { children: dedicated_2.DedicatedDiskSpeedNames.map(function (type) { return ((0, jsx_runtime_1.jsx)(antd_1.Radio.Button, __assign({ value: type }, { children: dedicated_2.DISK_NAMES[type] }), type)); }) })) })), (0, jsx_runtime_1.jsx)(antd_1.Form.Item, __assign({ label: "Performance" }, { children: renderDiskPerformance() }))] }));
    }
    function renderDedicatedVmInfo() {
        if (!showExplanations)
            return;
        return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: ["More information about VM types can be found at", " ", (0, jsx_runtime_1.jsx)(A_1.default, __assign({ href: "https://cloud.google.com/compute/docs/machine-types" }, { children: "GCP: machine families" })), "."] }));
    }
    function renderVmPerformance() {
        var _a, _b;
        if (vmMachine == null)
            return;
        var spec = ((_b = (_a = dedicated_3.PRICES.vms) === null || _a === void 0 ? void 0 : _a[vmMachine]) !== null && _b !== void 0 ? _b : {}).spec;
        if (spec == null) {
            return ((0, jsx_runtime_1.jsxs)("p", { children: ["Problem: the specifications of ", (0, jsx_runtime_1.jsx)("code", { children: vmMachine }), " are not known"] }));
        }
        return ((0, jsx_runtime_1.jsxs)("p", { children: ["Restarting your project while this license is active, will move your project on a virtual machine in ", (0, jsx_runtime_1.jsx)(site_name_1.default, {}), "'s cluster. This machine will allow you to use up to ", spec.cpu, " CPU cores and ", spec.mem, " G memory."] }));
    }
    function dedicatedVmOptions() {
        return (0, lodash_1.sortBy)(Object.entries(dedicated_3.PRICES.vms), function (_a) {
            var _b = __read(_a, 2), _ = _b[0], vm = _b[1];
            return "".concat(1000 + vm.spec.cpu, ":").concat(1000 + vm.spec.mem);
        }).map(function (_a) {
            var _b;
            var _c = __read(_a, 2), id = _c[0], vm = _c[1];
            return ((0, jsx_runtime_1.jsxs)(antd_1.Select.Option, __assign({ value: id }, { children: [(0, jsx_runtime_1.jsx)(Text, { children: (_b = vm.title) !== null && _b !== void 0 ? _b : vm.spec }), (0, jsx_runtime_1.jsxs)(Text, __assign({ style: { paddingLeft: "1em" }, type: "secondary" }, { children: ["(", (0, utils_1.money)(vm.price_day), " per day)"] }))] }), id));
        });
    }
    function renderDedicatedVM() {
        return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(antd_1.Form.Item, __assign({ label: "Type", name: "vm-machine", initialValue: null, extra: renderDedicatedVmInfo(), rules: [{ required: true, message: "Please select a VM type." }] }, { children: (0, jsx_runtime_1.jsx)(antd_1.Select, __assign({ onChange: function (val) {
                            form.setFieldsValue({ "vm-machine": val });
                            setVmMachine(val);
                            onChange();
                        } }, { children: dedicatedVmOptions() })) })), (0, jsx_runtime_1.jsx)(antd_1.Form.Item, __assign({ label: "Performance" }, { children: (0, jsx_runtime_1.jsx)("div", __assign({ style: { paddingTop: "5px" } }, { children: renderVmPerformance() })) }))] }));
    }
    function renderConfiguration() {
        switch (formType) {
            case "disk":
                return renderDedicatedDisk();
            case "vm":
                return renderDedicatedVM();
        }
    }
    function renderCost() {
        if (cost == null)
            return;
        var input = cost.input;
        if (input == null)
            return;
        var disabled = (input.type === "vm" && (input.start == null || input.end == null)) ||
            (input.type === "disk" && !diskNameValid);
        return ((0, jsx_runtime_1.jsx)(antd_1.Form.Item, __assign({ wrapperCol: { offset: 0, span: 24 } }, { children: (0, jsx_runtime_1.jsx)(add_box_1.AddBox, { cost: cost, form: form, cartError: cartError, setCartError: setCartError, router: router, dedicatedItem: true, disabled: disabled, noAccount: noAccount }) })));
    }
    return ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(cost_info_bar_1.InfoBar, { show: showInfoBar, cost: cost, router: router, form: form, cartError: cartError, setCartError: setCartError, noAccount: noAccount }), (0, jsx_runtime_1.jsx)(apply_license_to_project_1.ApplyLicenseToProject, { router: router }), (0, jsx_runtime_1.jsx)(sign_in_to_purchase_1.SignInToPurchase, { noAccount: noAccount }), (0, jsx_runtime_1.jsxs)(antd_1.Form, __assign({ form: form, style: {
                    marginTop: "15px",
                    margin: "auto",
                    border: "1px solid #ddd",
                    padding: "15px",
                }, name: "basic", labelCol: { span: 6 }, wrapperCol: { span: 18 }, autoComplete: "off", onValuesChange: onChange }, { children: [(0, jsx_runtime_1.jsx)(toggle_explanations_1.ToggleExplanations, { showExplanations: showExplanations, setShowExplanations: setShowExplanations }), renderTypeSelection(), formType != null && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [renderAdditionalInfo(), renderUsageAndDuration(), (0, jsx_runtime_1.jsx)(antd_1.Divider, __assign({ plain: true }, { children: "Confguration" })), renderConfiguration(), (0, jsx_runtime_1.jsx)(title_description_1.TitleDescription, { showExplanations: showExplanations }), renderCost()] }))] }))] }));
}
//# sourceMappingURL=dedicated.js.map