"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 loading_1 = __importDefault(require("components/share/loading"));
var antd_1 = require("antd");
var select_license_1 = __importDefault(require("./select-license"));
var avatar_1 = __importDefault(require("components/account/avatar"));
var misc_1 = require("@cocalc/util/misc");
var A_1 = __importDefault(require("components/misc/A"));
var post_1 = __importDefault(require("lib/api/post"));
var misc_2 = require("@cocalc/util/misc");
var edit_url_1 = __importDefault(require("lib/share/edit-url"));
var license_1 = require("./license");
var managed_1 = require("./managed");
var router_1 = require("next/router");
var copyable_1 = __importDefault(require("components/misc/copyable"));
var licensed_projects_1 = require("./licensed-projects");
function TitleId(_a) {
    var title = _a.title, project_id = _a.project_id, collaborators = _a.collaborators, account_id = _a.account_id, label = _a.label;
    return ((0, jsx_runtime_1.jsxs)("div", __assign({ style: { wordWrap: "break-word", wordBreak: "break-word" } }, { children: [collaborators.includes(account_id) ? ((0, jsx_runtime_1.jsx)(A_1.default, __assign({ href: (0, edit_url_1.default)({ project_id: project_id, type: "collaborator" }), external: true }, { children: title }))) : (title), label && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("br", {}), "Project Id:"] })), (0, jsx_runtime_1.jsx)(copyable_1.default, { value: project_id, size: "small" })] })));
}
function Collaborators(_a) {
    var collaborators = _a.collaborators;
    return ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: collaborators.map(function (account_id) { return ((0, jsx_runtime_1.jsx)(avatar_1.default, { account_id: account_id, size: 24, style: { marginRight: "2.5px" } }, account_id)); }) }));
}
function State(_a) {
    var state = _a.state;
    return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: (0, misc_2.capitalize)(state) });
}
function HowLicenseUsed(_a) {
    var _b;
    var account_id = _a.account_id;
    var router = (0, router_1.useRouter)();
    var _c = __read((0, react_1.useState)("".concat((_b = router.query.license_id) !== null && _b !== void 0 ? _b : "")), 2), license = _c[0], setLicense = _c[1];
    var _d = __read((0, react_1.useState)(""), 2), search = _d[0], setSearch = _d[1];
    var _e = __read((0, react_1.useState)(""), 2), error = _e[0], setError = _e[1];
    var _f = __read((0, react_1.useState)([]), 2), projects = _f[0], setProjects = _f[1];
    var _g = __read((0, react_1.useState)(false), 2), loading = _g[0], setLoading = _g[1];
    var _h = __read((0, react_1.useState)(false), 2), excludeMe = _h[0], setExcludeMe = _h[1];
    var columns = (0, react_1.useMemo)(function () {
        return [
            {
                responsive: ["xs"],
                render: function (_, project) { return ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(TitleId, __assign({}, project, { account_id: account_id, label: true })), (0, jsx_runtime_1.jsxs)("div", { children: ["Last Edited: ", (0, jsx_runtime_1.jsx)(licensed_projects_1.LastEdited, __assign({}, project))] }), (0, jsx_runtime_1.jsxs)("div", { children: ["State: ", (0, jsx_runtime_1.jsx)(State, __assign({}, project))] }), (0, jsx_runtime_1.jsxs)("div", { children: ["Collaborators: ", (0, jsx_runtime_1.jsx)(Collaborators, __assign({}, project))] }), (0, jsx_runtime_1.jsxs)("div", { children: ["Quota in use: ", (0, jsx_runtime_1.jsx)(managed_1.Quota, __assign({}, project))] })] })); },
            },
            {
                responsive: ["sm"],
                title: ((0, jsx_runtime_1.jsx)(antd_1.Popover, __assign({ placement: "bottom", title: "Project", content: (0, jsx_runtime_1.jsx)("div", __assign({ style: { maxWidth: "75ex" } }, { children: "This is the title and id of the project. If you are a collaborator on this project, then you can click the title to open the project." })) }, { children: "Project" }))),
                width: "30%",
                render: function (_, project) { return ((0, jsx_runtime_1.jsx)(TitleId, __assign({}, project, { account_id: account_id }))); },
                sorter: { compare: function (a, b) { return (0, misc_2.cmp)(a.title, b.title); } },
            },
            {
                responsive: ["sm"],
                title: "Last Edited",
                render: function (_, project) { return (0, jsx_runtime_1.jsx)(licensed_projects_1.LastEdited, __assign({}, project)); },
                sorter: { compare: function (a, b) { return (0, misc_2.cmp)(a.last_edited, b.last_edited); } },
            },
            {
                responsive: ["sm"],
                title: ((0, jsx_runtime_1.jsxs)(antd_1.Popover, __assign({ title: "Collaborators", content: (0, jsx_runtime_1.jsxs)("div", __assign({ style: { maxWidth: "75ex" } }, { children: ["These are the collaborators on this project. You are not necessarily included in this list, since this license can be applied to any project by somebody who knows the license code. Click the \"Exclude me\" checkbox to see only projects that you are ", (0, jsx_runtime_1.jsx)("b", { children: "not" }), " a collaborator on."] })) }, { children: ["Collaborators", (0, jsx_runtime_1.jsx)("div", __assign({ style: { fontWeight: 300 } }, { children: (0, jsx_runtime_1.jsx)(antd_1.Checkbox, __assign({ onChange: function (e) { return setExcludeMe(e.target.checked); }, checked: excludeMe }, { children: "Exclude me" })) }))] }))),
                render: function (_, project) { return (0, jsx_runtime_1.jsx)(Collaborators, __assign({}, project)); },
            },
            {
                responsive: ["sm"],
                title: "State",
                dataIndex: "state",
                key: "state",
                sorter: { compare: function (a, b) { return (0, misc_2.cmp)(a.state, b.state); } },
                render: function (_, project) { return (0, jsx_runtime_1.jsx)(State, __assign({}, project)); },
            },
            managed_1.quotaColumn,
        ];
    }, [account_id, excludeMe]);
    function load(license_id) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, err_1;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        setLicense(license_id);
                        setError("");
                        if (!license_id) return [3 /*break*/, 5];
                        setLoading(true);
                        setProjects([]);
                        _b.label = 1;
                    case 1:
                        _b.trys.push([1, 3, 4, 5]);
                        _a = setProjects;
                        return [4 /*yield*/, (0, post_1.default)("/licenses/get-projects-with-license", {
                                license_id: license_id,
                            })];
                    case 2:
                        _a.apply(void 0, [_b.sent()]);
                        return [3 /*break*/, 5];
                    case 3:
                        err_1 = _b.sent();
                        setError(err_1.message);
                        return [3 /*break*/, 5];
                    case 4:
                        setLoading(false);
                        return [7 /*endfinally*/];
                    case 5: return [2 /*return*/];
                }
            });
        });
    }
    (0, react_1.useEffect)(function () {
        // initial license load (e.g., from query param)
        if (license) {
            load(license);
        }
    }, []);
    return ((0, jsx_runtime_1.jsxs)("div", __assign({ style: { width: "100%", overflowX: "auto", minHeight: "50vh" } }, { children: [(0, jsx_runtime_1.jsx)("h3", { children: "How a License You Manage is Being Used" }), "Select a license you manage to see how it is being used. You can see", " ", (0, jsx_runtime_1.jsx)("i", { children: "all" }), " projects that have this license applied to them (even if you are not a collaborator on them!), remove licenses from projects, and view analytics about how the license has been used over time to better inform your decision making.", (0, jsx_runtime_1.jsx)("div", __assign({ style: { margin: "15px 0", width: "100%", textAlign: 'center' } }, { children: (0, jsx_runtime_1.jsx)(select_license_1.default, { disabled: loading, onSelect: function (license_id) {
                        router.push({
                            pathname: router.asPath.split("?")[0],
                            query: { license_id: license_id },
                        });
                        load(license_id);
                    }, license: license, style: { width: "100%", maxWidth: "90ex" } }) })), license && error && (0, jsx_runtime_1.jsx)(antd_1.Alert, { type: "error", message: error }), license && loading && ((0, jsx_runtime_1.jsx)(loading_1.default, { style: { fontSize: "16pt", margin: "auto" } })), (0, jsx_runtime_1.jsx)("div", __assign({ style: {
                    border: "1px solid lightgrey",
                    borderRadius: "5px",
                    padding: "15px",
                    backgroundColor: "#fafafa",
                    width: "100%",
                    maxWidth: "90ex",
                    margin: "auto",
                } }, { children: license ? ((0, jsx_runtime_1.jsx)(license_1.Details, { license_id: license })) : ((0, jsx_runtime_1.jsx)("div", __assign({ style: { textAlign: "center", fontSize: "13pt" } }, { children: "Select a license above." }))) })), license && !loading && projects.length > 1 && ((0, jsx_runtime_1.jsx)("div", __assign({ style: { margin: "15px 0", maxWidth: "50ex" } }, { children: (0, jsx_runtime_1.jsx)(antd_1.Input.Search, { placeholder: "Search project titles...", allowClear: true, onChange: function (e) { return setSearch(e.target.value); }, style: { width: "100%" } }) }))), license && !loading && ((0, jsx_runtime_1.jsx)(antd_1.Table, { columns: columns, dataSource: doSearch(projects, search, excludeMe, account_id), rowKey: "project_id", style: { marginTop: "15px" }, pagination: { hideOnSinglePage: true, pageSize: 100 } }))] })));
}
exports.default = HowLicenseUsed;
function doSearch(data, search, excludeMe, account_id) {
    var e_1, _a;
    var _b, _c;
    var v = (0, misc_1.search_split)(search.toLowerCase().trim());
    var w = [];
    try {
        for (var data_1 = __values(data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) {
            var x = data_1_1.value;
            if (excludeMe && ((_b = x["collaborators"]) === null || _b === void 0 ? void 0 : _b.includes(account_id)))
                continue;
            if (x["search"] == null) {
                x["search"] = "".concat((_c = x["title"]) !== null && _c !== void 0 ? _c : "", " ").concat(x["id"]).toLowerCase();
            }
            if ((0, misc_1.search_match)(x["search"], v)) {
                w.push(x);
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return w;
}
//# sourceMappingURL=how-used.js.map