/*
 * DataStax handle the links to internal review docs business.
 * Uses cookies and key press combo event handler.
 */

function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/; Secure; SameSite=None";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) === 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

function setupDocsreviewDisplay() {
    document.addEventListener('keydown', (event) => {
        const keyName = event.key;
        var timestamp = new Date();
        if ( event.ctrlKey && event.altKey && event.keyCode == 52 ) {
            document.getElementById('docsreviewLink').setAttribute("style", "display: inline-block; padding-left: 12px;");
            console.log("Ctrl+Alt+4 pressed: show docsreview link.");
            createCookie("ds.internal.docsreview", true, 365);
        }
    }, false);
}

function linkToDocsreview() {
    // create a new div element in the right top navigation tools
    var rightToolsElementArray = document.getElementsByClassName('wh_right_tools');
    var rightToolsElement = rightToolsElementArray[0];
    if ( rightToolsElement === undefined ) {
        return
    }
    var divElement = document.createElement('div');
    var styleAttributeValue = 'display: none; padding-left: 12px;'
    divElement.setAttribute("id", "docsreviewLink");
    if (readCookie("ds.internal.docsreview")) {
        styleAttributeValue = 'display: inline-block; padding-left: 12px;'
    }
    divElement.setAttribute("style", styleAttributeValue);
    // create a link to the same topic on docsreview
    var docsreviewLink = document.createElement("a");
    docsreviewLink.setAttribute("class", "glyphicon glyphicon-comment");
    var targetUrl = "https://docsreview.sjc.dsinternal.org" + window.location.pathname;
    docsreviewLink.setAttribute("href", targetUrl);
    docsreviewLink.setAttribute("title", "Review this page on docsreview.");
    // insert the new link on the page after the print icon
    divElement.appendChild(docsreviewLink);
    rightToolsElement.appendChild(divElement);
    // set up handler for keypress to display event
    setupDocsreviewDisplay();
}
