"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.initHeader = initHeader;
exports.rebuildHeader = rebuildHeader;
exports.createBanner = createBanner;
exports.createHelpMenu = createHelpMenu;
exports.createLoginSignUpButtons = createLoginSignUpButtons;
exports.createUserMenuButton = createUserMenuButton;
exports.createUserMenuLink = createUserMenuLink;
exports.createUserMenu = createUserMenu;
exports.createUserMenuItem = createUserMenuItem;
exports.getProfileImg = getProfileImg;
const index_1 = require("../index");
const solid_logic_1 = require("solid-logic");
const login_1 = require("../login/login");
// import { loginStatusBox, authSession, currentUser } from '../authn/authn'
const widgets = __importStar(require("../widgets"));
const style_1 = require("../style");
const empty_profile_1 = require("./empty-profile");
const headerFooterHelpers_1 = require("../utils/headerFooterHelpers");
/**
 * menu icons
*/
const DEFAULT_HELP_MENU_ICON = index_1.icons.iconBase + 'noun_help.svg';
const DEFAUL_SOLID_ICON_URL = 'https://solidproject.org/assets/img/solid-emblem.svg';
/**
 * Initialize header component, the header object returned depends on whether the user is authenticated.
 * @param store the data store
 * @param userMenuList a list of menu items when the user is logged in
 * @param options allow the header to be customized with a personalized logo, help icon and a help menu list of links or buttons.
 * @returns a header for an authenticated user with menu items given or a login screen
 */
async function initHeader(store, userMenuList, options) {
    const header = document.getElementById('PageHeader');
    if (!header) {
        return;
    }
    const pod = (0, headerFooterHelpers_1.getPod)();
    rebuildHeader(header, store, pod, userMenuList, options)();
    solid_logic_1.authSession.events.on('logout', rebuildHeader(header, store, pod, userMenuList, options));
    solid_logic_1.authSession.events.on('login', rebuildHeader(header, store, pod, userMenuList, options));
}
/**
 * @ignore exporting this only for the unit test
 */
function rebuildHeader(header, store, pod, userMenuList, options) {
    return async () => {
        const user = solid_logic_1.authn.currentUser();
        header.innerHTML = '';
        header.appendChild(await createBanner(store, pod, user, userMenuList, options));
    };
}
/**
 * @ignore exporting this only for the unit test
 */
async function createBanner(store, pod, user, userMenuList, options) {
    const podLink = document.createElement('a');
    podLink.href = pod.uri;
    podLink.setAttribute('style', style_1.style.headerBannerLink);
    const image = document.createElement('img');
    if (options) {
        image.src = options.logo ? options.logo : DEFAUL_SOLID_ICON_URL;
    }
    image.setAttribute('style', style_1.style.headerBannerIcon);
    podLink.appendChild(image);
    const userMenu = user
        ? await createUserMenu(store, user, userMenuList)
        : createLoginSignUpButtons();
    const banner = document.createElement('div');
    banner.setAttribute('style', style_1.style.headerBanner);
    banner.appendChild(podLink);
    const leftSideOfHeader = document.createElement('div');
    leftSideOfHeader.setAttribute('style', style_1.style.headerBannerRightMenu);
    leftSideOfHeader.appendChild(userMenu);
    if (options && options.helpMenuList) {
        const helpMenu = createHelpMenu(options, options.helpMenuList);
        leftSideOfHeader.appendChild(helpMenu);
    }
    banner.appendChild(leftSideOfHeader);
    return banner;
}
/**
 * @ignore exporting this only for the unit test
 */
function createHelpMenu(options, helpMenuItems) {
    if (!helpMenuItems)
        return;
    const helpMenuList = document.createElement('ul');
    helpMenuList.setAttribute('style', style_1.style.headerUserMenuList);
    helpMenuItems.forEach(function (menuItem) {
        const menuItemType = menuItem.url ? 'url' : 'onclick';
        if (menuItemType === 'url') {
            helpMenuList.appendChild(createUserMenuItem(createUserMenuLink(menuItem.label, menuItem.url, menuItem.target)));
        }
        else {
            helpMenuList.appendChild(createUserMenuItem(createUserMenuButton(menuItem.label, menuItem.onclick)));
        }
    });
    const helpMenu = document.createElement('nav');
    helpMenu.setAttribute('style', style_1.style.headerUserMenuNavigationMenuNotDisplayed);
    helpMenu.setAttribute('aria-hidden', 'true');
    helpMenu.setAttribute('id', 'helperNav');
    helpMenu.appendChild(helpMenuList);
    const helpMenuContainer = document.createElement('div');
    helpMenuContainer.setAttribute('style', style_1.style.headerBannerUserMenu);
    helpMenuContainer.appendChild(helpMenu);
    const helpMenuTrigger = document.createElement('button');
    helpMenuTrigger.setAttribute('style', style_1.style.headerUserMenuTrigger);
    helpMenuTrigger.type = 'button';
    const helpMenuIcon = document.createElement('img');
    helpMenuIcon.src = (options && options.helpIcon) ? options.helpIcon : index_1.icons.iconBase + DEFAULT_HELP_MENU_ICON;
    helpMenuIcon.setAttribute('style', style_1.style.headerUserMenuTriggerImg);
    helpMenuContainer.appendChild(helpMenuTrigger);
    helpMenuTrigger.appendChild(helpMenuIcon);
    const throttledMenuToggle = (0, headerFooterHelpers_1.throttle)((event) => toggleMenu(event, helpMenuTrigger, helpMenu), 50);
    helpMenuTrigger.addEventListener('click', throttledMenuToggle);
    let timer = setTimeout(() => null, 0);
    helpMenuContainer.addEventListener('mouseover', event => {
        clearTimeout(timer);
        throttledMenuToggle(event);
        const nav = document.getElementById('helperNav');
        nav?.setAttribute('style', style_1.style.headerUserMenuNavigationMenu);
    });
    helpMenuContainer.addEventListener('mouseout', event => {
        timer = setTimeout(() => throttledMenuToggle(event), 200);
        const nav = document.getElementById('helperNav');
        nav?.setAttribute('style', style_1.style.headerUserMenuNavigationMenuNotDisplayed);
    });
    return helpMenuContainer;
}
/**
 * @ignore exporting this only for the unit test
 */
function createLoginSignUpButtons() {
    const profileLoginButtonPre = document.createElement('div');
    profileLoginButtonPre.setAttribute('style', style_1.style.headerBannerLogin);
    profileLoginButtonPre.appendChild((0, login_1.loginStatusBox)(document, null, {}));
    return profileLoginButtonPre;
}
/**
 * @ignore exporting this only for the unit test
 */
function createUserMenuButton(label, onClick) {
    const button = document.createElement('button');
    button.setAttribute('style', style_1.style.headerUserMenuButton);
    button.onmouseover = function () {
        button.setAttribute('style', style_1.style.headerUserMenuButtonHover);
    };
    button.onmouseout = function () {
        button.setAttribute('style', style_1.style.headerUserMenuButton);
    };
    button.addEventListener('click', onClick);
    button.innerText = label;
    return button;
}
/**
 * @ignore exporting this only for the unit test
 */
function createUserMenuLink(label, href, target) {
    const link = document.createElement('a');
    link.setAttribute('style', style_1.style.headerUserMenuLink);
    link.onmouseover = function () {
        link.setAttribute('style', style_1.style.headerUserMenuLinkHover);
    };
    link.onmouseout = function () {
        link.setAttribute('style', style_1.style.headerUserMenuLink);
    };
    link.href = href;
    link.innerText = label;
    if (target)
        link.target = target;
    return link;
}
/**
 * @ignore exporting this only for the unit test
 */
async function createUserMenu(store, user, userMenuList) {
    const fetcher = store.fetcher;
    if (fetcher) {
        // Making sure that Profile is loaded before building menu
        await fetcher.load(user);
    }
    const loggedInMenuList = document.createElement('ul');
    loggedInMenuList.setAttribute('style', style_1.style.headerUserMenuList);
    if (userMenuList) {
        userMenuList.forEach(function (menuItem) {
            const menuItemType = menuItem.url ? 'url' : 'onclick';
            if (menuItemType === 'url') {
                loggedInMenuList.appendChild(createUserMenuItem(createUserMenuLink(menuItem.label, menuItem.url, menuItem.target)));
            }
            else {
                loggedInMenuList.appendChild(createUserMenuItem(createUserMenuButton(menuItem.label, menuItem.onclick)));
            }
        });
    }
    const loggedInMenu = document.createElement('nav');
    loggedInMenu.setAttribute('style', style_1.style.headerUserMenuNavigationMenuNotDisplayed);
    loggedInMenu.setAttribute('aria-hidden', 'true');
    loggedInMenu.setAttribute('id', 'loggedInNav');
    loggedInMenu.appendChild(loggedInMenuList);
    const loggedInMenuTrigger = document.createElement('button');
    loggedInMenuTrigger.setAttribute('style', style_1.style.headerUserMenuTrigger);
    loggedInMenuTrigger.type = 'button';
    const profileImg = getProfileImg(store, user);
    if (typeof profileImg === 'string') {
        loggedInMenuTrigger.innerHTML = profileImg;
    }
    else {
        loggedInMenuTrigger.appendChild(profileImg);
    }
    const loggedInMenuContainer = document.createElement('div');
    loggedInMenuContainer.setAttribute('style', style_1.style.headerBannerUserMenuNotDisplayed);
    loggedInMenuContainer.appendChild(loggedInMenuTrigger);
    loggedInMenuContainer.appendChild(loggedInMenu);
    const throttledMenuToggle = (0, headerFooterHelpers_1.throttle)((event) => toggleMenu(event, loggedInMenuTrigger, loggedInMenu), 50);
    loggedInMenuTrigger.addEventListener('click', throttledMenuToggle);
    let timer = setTimeout(() => null, 0);
    loggedInMenuContainer.addEventListener('mouseover', event => {
        clearTimeout(timer);
        throttledMenuToggle(event);
        const nav = document.getElementById('loggedInNav');
        nav?.setAttribute('style', style_1.style.headerUserMenuNavigationMenu);
    });
    loggedInMenuContainer.addEventListener('mouseout', event => {
        timer = setTimeout(() => throttledMenuToggle(event), 200);
        const nav = document.getElementById('loggedInNav');
        nav?.setAttribute('style', style_1.style.headerUserMenuNavigationMenuNotDisplayed);
    });
    return loggedInMenuContainer;
}
/**
 * @ignore exporting this only for the unit test
 */
function createUserMenuItem(child) {
    const menuProfileItem = document.createElement('li');
    menuProfileItem.setAttribute('style', style_1.style.headerUserMenuListItem);
    menuProfileItem.appendChild(child);
    return menuProfileItem;
}
/**
 * @ignore exporting this only for the unit test
 */
function getProfileImg(store, user) {
    let profileUrl = null;
    try {
        profileUrl = widgets.findImage(user);
        if (!profileUrl) {
            return empty_profile_1.emptyProfile;
        }
    }
    catch {
        return empty_profile_1.emptyProfile;
    }
    const profileImage = document.createElement('div');
    profileImage.setAttribute('style', style_1.style.headerUserMenuPhoto);
    profileImage.style.backgroundImage = `url(${profileUrl})`;
    return profileImage;
}
/**
 * @internal
 */
function toggleMenu(event, trigger, menu) {
    const isExpanded = trigger.getAttribute('aria-expanded') === 'true';
    const expand = event.type === 'mouseover';
    const close = event.type === 'mouseout';
    if ((isExpanded && expand) || (!isExpanded && close)) {
        return;
    }
    trigger.setAttribute('aria-expanded', (!isExpanded).toString());
    menu.setAttribute('aria-hidden', isExpanded.toString());
}
//# sourceMappingURL=index.js.map