"use strict";
/*
 *  This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
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 });
exports.useTimeFixer = exports.loadDateRange = exports.getType = void 0;
var billing_1 = require("@cocalc/util/consts/billing");
var timecalcs_1 = require("@cocalc/util/stripe/timecalcs");
var use_customize_1 = __importDefault(require("lib/use-customize"));
var moment_1 = __importDefault(require("moment"));
var react_1 = require("react");
// site license type in a form, we have 4 forms hence 4 types
// later, this will be mapped to just "LicenseType", where boost and regular
// are "quota" and item.boost = true|false.
function getType(item) {
    var descr = item.description;
    if (descr.dedicated_disk != null && descr.dedicated_disk !== false) {
        return "disk";
    }
    else if (descr.dedicated_vm != null && descr.dedicated_vm !== false) {
        return "vm";
    }
    else if (descr.boost === true) {
        return "boost";
    }
    else {
        return "regular";
    }
}
exports.getType = getType;
// when loading an item from the cart/saved for later, we have to fix the start/end dates to be at least "today" at the start of the day in the users time zone.
function loadDateRange(range) {
    var e_1, _a;
    if (range == null) {
        var now = new Date();
        return [(0, timecalcs_1.startOfDay)(now), (0, timecalcs_1.endOfDay)(now)];
    }
    try {
        for (var _b = __values([0, 1]), _c = _b.next(); !_c.done; _c = _b.next()) {
            var idx = _c.value;
            var v = range[idx];
            if (typeof v === "string") {
                range[idx] = new Date(v);
            }
        }
    }
    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; }
    }
    if (range[0] instanceof Date) {
        var today = (0, timecalcs_1.startOfDay)(new Date());
        var prevStart = range[0];
        if (range[0].getTime() < today.getTime()) {
            range[0] = today;
        }
        // we we have to shift the start, move the end forward as well and preserve the duration.
        if (range[1] instanceof Date) {
            if (range[0].getTime() > range[1].getTime()) {
                var days = (0, timecalcs_1.getDays)({ start: prevStart, end: range[1] });
                range[1] = (0, timecalcs_1.endOfDay)(new Date(Date.now() + billing_1.ONE_DAY_MS * days));
            }
        }
    }
    return range;
}
exports.loadDateRange = loadDateRange;
/**
 * use serverTime to fix the users exact time and return an object with these properties:
 * - offset: difference in milliseconds between server time and user time
 * - timezone: the user's timezone
 * - serverTime: the Date object of serverTime
 * - userTime: the Date object of userTime
 * - function toServerTime(date): converts a Date object from the user's time to the server time
 *
 * @param serverTime -- milliseconds since epoch from the server
 */
function useTimeFixer() {
    var customizeServerTime = (0, use_customize_1.default)().serverTime;
    return (0, react_1.useMemo)(function () {
        // server time is supposed to be always set, but just in case …
        if (customizeServerTime == null) {
            console.warn("WARNING: customize.serverTime is not set, using Date.now()");
        }
        var serverTime = customizeServerTime !== null && customizeServerTime !== void 0 ? customizeServerTime : Date.now();
        var localTime = Date.now();
        // important: useMemo, b/c we calculate the offset only *once* when the page loads, not each time the hook is called
        var offset = localTime - serverTime;
        function toTimestamp(date) {
            return (0, moment_1.default)(date).toDate().getTime();
        }
        function toServerTime(date) {
            return new Date(toTimestamp(date) - offset);
        }
        function fromServerTime(date) {
            return new Date(toTimestamp(date) + offset);
        }
        return {
            offset: offset,
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            serverTimeDate: new Date(serverTime),
            toServerTime: toServerTime,
            fromServerTime: fromServerTime,
        };
    }, []);
}
exports.useTimeFixer = useTimeFixer;
//# sourceMappingURL=util.js.map