"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SearchResultItem = exports.formatDate = void 0;
const react_1 = __importDefault(require("react"));
const bytes_1 = __importDefault(require("bytes"));
const parseISO_1 = __importDefault(require("date-fns/parseISO"));
const formatDistanceToNow_1 = __importDefault(require("date-fns/formatDistanceToNow"));
const react_router_dom_1 = require("react-router-dom");
const Tooltip_1 = require("../tooltip/Tooltip");
const Icon_1 = require("../icon/Icon");
const activity_icon_png_1 = __importDefault(require("../assets/activity-icon.png"));
/**
 * Return an equivalent to moment(date).format('L') without moment
 * @param {*} dateObject
 */
const formatDate = dateObject => new Date(dateObject).toISOString().split('T')[0];
exports.formatDate = formatDate;
const SearchResultItem = ({ node, profile, datasetTypeSelected, hasEditPermissions, }) => {
    const isAdmin = profile?.admin;
    const hasEdit = hasEditPermissions(node.permissions, profile?.sub) || isAdmin;
    const heading = node.latestSnapshot.description?.Name;
    const summary = node.latestSnapshot?.summary;
    const datasetId = node.id;
    const numSessions = summary?.sessions.length > 0 ? summary.sessions.length : 1;
    const numSubjects = summary?.subjects.length > 0 ? summary.subjects.length : 1;
    const accessionNumber = (react_1.default.createElement("span", { className: "result-summary-meta" },
        react_1.default.createElement("strong", null, "Openneuro Accession Number:"),
        react_1.default.createElement("span", null,
            " ",
            node.id)));
    const sessions = (react_1.default.createElement("span", { className: "result-summary-meta" },
        react_1.default.createElement("strong", null, "Sessions: "),
        react_1.default.createElement("span", null, numSessions.toLocaleString())));
    const ages = value => {
        if (value) {
            const ages = value.filter(x => x);
            if (ages.length === 0)
                return 'N/A';
            else if (ages.length === 1)
                return ages[0];
            else
                return `${Math.min(...ages)} - ${Math.max(...ages)}`;
        }
        else
            return 'N/A';
    };
    const agesRange = (react_1.default.createElement("span", { className: "result-summary-meta" },
        react_1.default.createElement("strong", null,
            node?.metadata?.ages?.length === 1
                ? "Participant's Age"
                : "Participants' Ages",
            ":",
            ' '),
        react_1.default.createElement("span", null, ages(summary?.subjectMetadata?.map(subject => subject.age)))));
    const subjects = (react_1.default.createElement("span", { className: "result-summary-meta" },
        react_1.default.createElement("strong", null, " Participants: "),
        react_1.default.createElement("span", null, numSubjects.toLocaleString())));
    const size = (react_1.default.createElement("span", { className: "result-summary-meta" },
        react_1.default.createElement("strong", null, "Size: "),
        react_1.default.createElement("span", null, (0, bytes_1.default)(node?.latestSnapshot?.size) || "unknown")));
    const files = (react_1.default.createElement("span", { className: "result-summary-meta" },
        react_1.default.createElement("strong", null, "Files: "),
        react_1.default.createElement("span", null, summary?.totalFiles.toLocaleString())));
    const dateAdded = (0, exports.formatDate)(node.created);
    const dateAddedDifference = (0, formatDistanceToNow_1.default)((0, parseISO_1.default)(node.created));
    let lastUpdatedDate;
    if (node.snapshots.length) {
        const dateUpdated = (0, exports.formatDate)(node.snapshots[node.snapshots.length - 1].created);
        const dateUpdatedDifference = (0, formatDistanceToNow_1.default)((0, parseISO_1.default)(node.snapshots[node.snapshots.length - 1].created));
        lastUpdatedDate = (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement("span", { className: "updated-divider" }, "|"),
            react_1.default.createElement("div", { className: "updated-date" },
                react_1.default.createElement("span", null, "Updated: "),
                dateUpdated,
                " - ",
                dateUpdatedDifference,
                " ago")));
    }
    const uploader = (react_1.default.createElement("div", { className: "uploader" },
        react_1.default.createElement("span", null, "Uploaded by: "),
        node.uploader.name,
        " on ",
        dateAdded,
        " - ",
        dateAddedDifference,
        " ago"));
    const downloads = node.analytics.downloads
        ? node.analytics.downloads.toLocaleString() + ' Downloads \n'
        : '';
    const views = node.analytics.views
        ? node.analytics.views.toLocaleString() + ' Views \n'
        : '';
    const following = node.followers.length
        ? node.followers.length.toLocaleString() + ' Follower \n'
        : '';
    const stars = node.stars.length
        ? node.stars.length.toLocaleString() + ' Bookmarked'
        : '';
    const activtyTooltip = downloads + views + following + stars;
    const activityIcon = (react_1.default.createElement(Tooltip_1.Tooltip, { tooltip: activtyTooltip, flow: "up", className: "result-icon result-activity-icon" },
        react_1.default.createElement(Icon_1.Icon, { imgSrc: activity_icon_png_1.default, iconSize: "22px", label: "activity", iconOnly: true })));
    const sharedWithIcon = (react_1.default.createElement(Tooltip_1.Tooltip, { tooltip: "Shared with me", flow: "up", className: "result-icon result-shared-icon" },
        react_1.default.createElement(Icon_1.Icon, { icon: "fas fa-user", color: "rgb(119,191,217)", iconSize: "16px", label: "Shared With", iconOnly: true })));
    const publicIcon = (react_1.default.createElement(Tooltip_1.Tooltip, { tooltip: "Visible to all viewers", flow: "up", className: "result-icon result-publlic-icon" },
        react_1.default.createElement(Icon_1.Icon, { icon: "fas fa-globe", color: "rgb(116,181,105)", iconSize: "16px", label: "Public", iconOnly: true })));
    const errorsIcon = hasEdit && (react_1.default.createElement(Tooltip_1.Tooltip, { tooltip: "Invalid", flow: "up", className: "result-icon result-errors-icon" },
        react_1.default.createElement(Icon_1.Icon, { icon: "fas fa-exclamation-circle", color: "rgb(202,97,86)", iconSize: "16px", label: "Invalid", iconOnly: true })));
    const _list = (type, items) => {
        if (items && items.length > 0) {
            return (react_1.default.createElement(react_1.default.Fragment, null,
                react_1.default.createElement("strong", null,
                    type,
                    ":"),
                react_1.default.createElement("div", null, items.map((item, index) => (react_1.default.createElement("span", { className: "list-item", key: index }, item))))));
        }
        else {
            return null;
        }
    };
    const invalid = !node.latestSnapshot.issues ||
        node.latestSnapshot.issues.some(issue => issue.severity === 'error');
    const shared = !node.public && node.uploader.id !== profile.sub;
    const MyDatasetsPage = datasetTypeSelected === 'My Datasets';
    const datasetPerms = node.permissions.userPermissions.map(item => {
        if (item.user.id === profile?.sub && item.access !== null) {
            if (item.access === 'ro') {
                return 'Read Only';
            }
            else if (item.access === 'rw') {
                return 'Edit';
            }
            else {
                return 'Admin';
            }
        }
        else {
            return null;
        }
    });
    const datasetOwenerIcons = (react_1.default.createElement("div", { className: "owner-icon-wrap" },
        node.public ? publicIcon : null,
        shared ? sharedWithIcon : null,
        invalid ? errorsIcon : null));
    const modalityList = summary?.modalities.length ? (react_1.default.createElement("div", { className: "modality-list" }, _list(react_1.default.createElement(react_1.default.Fragment, null, summary?.modalities.length === 1 ? 'Modality' : 'Modalities'), summary?.modalities))) : null;
    const taskList = summary?.tasks.length ? (react_1.default.createElement("div", { className: "task-list" }, _list(react_1.default.createElement(react_1.default.Fragment, null, "Tasks"), summary?.tasks))) : null;
    const tracers = summary?.pet?.TracerName?.length ? (react_1.default.createElement("div", { className: "tracers-list" }, _list(react_1.default.createElement(react_1.default.Fragment, null, summary?.pet?.TracerName.length === 1
        ? 'Radiotracer'
        : 'Radiotracers'), summary?.pet?.TracerName))) : null;
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement("div", { className: "grid grid-nogutter search-result" },
            react_1.default.createElement("div", { className: "col col-9" },
                react_1.default.createElement("h3", null,
                    react_1.default.createElement(react_router_dom_1.Link, { to: '/datasets/' + datasetId }, heading)),
                react_1.default.createElement("div", { className: "result-upload-info" },
                    uploader,
                    lastUpdatedDate)),
            react_1.default.createElement("div", { className: "col col-3 col-sm" },
                MyDatasetsPage && (react_1.default.createElement("div", { className: "dataset-permissions-tag" },
                    react_1.default.createElement("small", null,
                        "Access: ",
                        datasetPerms))),
                react_1.default.createElement("div", { className: "result-icon-wrap" },
                    datasetOwenerIcons,
                    activityIcon)),
            react_1.default.createElement("div", { className: "col col-12 result-meta-body" },
                modalityList,
                taskList,
                tracers),
            react_1.default.createElement("div", { className: "result-meta-footer" },
                accessionNumber,
                sessions,
                subjects,
                agesRange,
                size,
                files))));
};
exports.SearchResultItem = SearchResultItem;
