const voyagerElement = document.getElementById("voyager");
const ecorpusContainerElement = document.getElementById("ecorpusContainerId");
const shadowRootElement = document.getElementById("voyager").shadowRoot;
const submenus = document.getElementsByClassName("submenu");
const menuItems = document.getElementsByClassName("menu-item");
const toursArticleContainerElement = document.getElementById("toursArticleContainer");
const toursArticleElement = document.getElementById("toursArticleId");
// const resetButtonElement = shadowRootElement.getElementById("main-reset");
const explodedViewInstructionsElement = document.getElementById('explodedViewInstructions');
const overlayArticleBlurElement = document.getElementById("overlayArticleBlur");
/*const welcomeArticleElement = document.getElementById("welcomeArticleId");
const tourStepsElements = document.getElementById("tourButtons").getElementsByClassName("tour-step");*/
// const backdropBlurElement = document.getElementById("backdropBlurId");
// const zodiacRangeElement = document.getElementById("zodiacRange");
console.log("VOYAGER ELEMENT ", voyagerElement);
const articles = document.getElementsByClassName("articleContainer");
const sceneLink = voyagerElement.attributes.root.value;

let currentPage;
let stepTimeoutID;

// ============ UTILS FOR VOYAGER UI ==============
let toursVisible = false;
let annotationVisible = false;
function setToursVisibility(bool) {
    if (toursVisible != bool) {
        voyagerElement.toggleTours();
        toursVisible = bool;
    }
}

function setAnnotationsVisibility(bool) {
    if (annotationVisible != bool) {
        voyagerElement.toggleAnnotations();
        annotationVisible = bool;
    }
}

function resetVoyager() {
    resetButtonElement.click();
    setToursVisibility(false);
    setTimeout(() => voyagerElement.setLanguage(languageSelect.value), 100); // TODO cleanup ?
}

// Hide or make visible a blur div in front of the voyager sccene (and anything with z-index <4)
function blurs(bool) {
    backdropBlurElement.style = 'visibility: ' + (bool ? 'visible;' : 'hidden;')
}

// ========== INTERNATIONALISATION ========
voyagerElement.onload = "setLanguage(languageSelect.value); console.log('HERE !', this),  this.setTourStep(0, 0, false)"
let currentLanguage = "fr";

const translatedElements = document.getElementsByClassName("translate");
i18n = {
};

function setLanguage(language) {
    voyagerElement.setLanguage(language);
    if (currentLanguage != language) {
        currentLanguage = language;
        setArticleContent(welcomeArticleElement, "new-article-5WNTa4aRHqc2");
        for (element of translatedElements) {
            console.log(element);
            element.innerHTML = i18n[element.id][language];
        }
    }
}

// ====== CHANGING VOYAGER CSS =====
const shadowRootStyleTag = document.createElement("style");
shadowRootStyleTag.textContent = "\
sv-content-view, sv-chrome-view {\
    --color-accent-1-rgb: 3, 62, 92;\
    --color-text : #f8f7e5  \
}\
.sv-content-split .sv-reader-container {margin-top: 0px;}\
.sv-nav-button:nth-of-type(2) {visibility:hidden}\
.sv-standard-annotation, .sv-extended-annotation{\
    color: var(--color-text);\
    background-color: rgba(var(--color-accent-1-rgb),0.75);\
    font-family: 'Source Sans 3', sans-serif;\
    font-size: 1.2rem;\
    .sv-title{\
        font-weight: normal;\
    }\
    p {\
        font-family: 'Source Sans 3', sans-serif;\
        font-weight: lighter;\
        font-size: 1rem;\
        color: var(--color-text);\
    }\
}\
.sv-standard-annotation.sv-expanded, .sv-extended-annotation.sv-expanded {\
    background-color: rgba(var(--color-accent-1-rgb),1);\
}\
.sv-article h1:before{\
    background-color: rgba(var(--color-accent-1-rgb),1); \
}\
.sv-article h1 , .sv-article p {\
    font-family: 'Source Sans 3', 'Hind Siliguri', sans-serif;\
}\
.sv-blue-bar{\
    background-color: rgba(var(--color-accent-1-rgb),0.85);\
    border-left: 1px solid rgba(var(--color-accent-1-rgb),0.5);\
    border-right: 1px solid rgba(var(--color-accent-1-rgb),0.5);\
    color: var(--color-text);\
    .ff-icon{\
         fill:currentColor;\
    }\
}\
.sv-blue-bar .sv-section {\
    border-top:  1px solid rgba(var(--color-accent-1-rgb),0.5);\
}\
.sv-blue-bar  .sv-section-trail {\
    border-left:  1px solid rgba(var(--color-accent-1-rgb),0.5);\
}\
.sv-tour-menu{\
  left: 252px;\
}\
.sv-chrome-view{\
    backgroundelement:transparent;\
    sv-tag-cloud{\
        display: none;\
    }\
}\
sv-content-view > div > ff-splitter{\
    display: none;\
}\
sv-content-view > div > div:nth-child(3){\
    display: none;\
}\
.sv-scene-view.sv-blur {\
    filter: none;\
}\
.sv-content-stack .sv-reader-container{\
    display: none;\
}\
";
shadowRootElement.appendChild(shadowRootStyleTag);
// resetButtonElement.style = "visibility:hidden;";

// // ==================== LOADING AND CHANGING ARTICLES ================
//setArticleContent(welcomeArticleElement, "new-article-5WNTa4aRHqc2");
// setArticleContent(zodiacArticleElement, "new-article-ecjibrJMHJ9p");
function setArticleContent(articleHTMLElement, article_uid) {
    const req = new XMLHttpRequest();
    req.addEventListener("load", () => {
        console.log("set Article Content");
        let article = new DOMParser().parseFromString(req.response, "text/html");
        //Rewritting relative links to absolute ones.
        for (attr of ['src', 'href']) {
            linksElement = article.querySelectorAll(`[${attr}]`)
            for (element of linksElement) {
                if ((!(element.attributes[attr].value.indexOf('http://') === 0)) && (!(element.attributes[attr].value.indexOf('https://') === 0))) {
                    element.attributes[attr].value = sceneLink + "articles/" + element.attributes[attr].value;
                }
            }
        }
        articleHTMLElement.innerHTML = article.body.innerHTML;
        //addTouchTooltips(articleHTMLElement);
        //addBiblioLinks(articleHTMLElement);
        //console.log('articleHTMLElement.closest(".scrollableTooltipContainer")', articleHTMLElement.closest("s.crollableTooltipContainer"));
        //articleHTMLElement.closest(".scrollableTooltipContainer").addEventListener("scroll", removeAllTooltips);
    });
    req.open("GET", sceneLink + "articles/" + article_uid + "-" + currentLanguage.toUpperCase() + ".html");
    req.send();
}

function closeArticle() {
    toursArticleContainerElement.style.display = "none";
    voyagerElement.application.documentProvider.activeComponent.setup.reader.ins.articleId.setValue("");
}

// ==================== HANDLING PAGES ==============================

let elementByPages = {
    NoPage: document.getElementsByClassName("noPage"),
    comprendrePage: document.getElementsByClassName("comprendrePage"),
    deconstruirePage: document.getElementsByClassName("deconstruirePage"),
    experimenterPage: document.getElementsByClassName("experimenterPage"),
    declenchementPage: document.getElementsByClassName("declenchementPage"),
}

function showPage(pageName, overlay = false) {
    currentPage = pageName;
    console.log(currentPage);
    for (const [key, htmlElements] of Object.entries(elementByPages)) {
        for (element of htmlElements) {
            if (element.classList.contains(pageName)) {
                element.style.visibility = "visible"
            } else if (!overlay) {
                element.style.visibility = "hidden"
            }
        }
    }

    if (pageName == "deconstruirePage") {
        const shadowRootStyleTag = document.createElement("style");

        shadowRootStyleTag.textContent = "\
        .sv-standard-annotation, .sv-extended-annotation{\
            border: 1px #ff0000 solid;\
            animation: blink 1s;\
            animation-iteration-count: 5;\
        }\
        @keyframes blink { 50% { border-color:#fff ; } }\
        }\
    ";
        shadowRootElement.appendChild(shadowRootStyleTag);
        explodedViewInstructionsElement.classList.add("disapearing");
        setTimeout(() => {
            shadowRootElement.removeChild(shadowRootElement.lastChild);
            explodedViewInstructionsElement.style = "visibility: hidden";
            explodedViewInstructionsElement.classList.remove("disapearing")
        }, 5000)
    }

    if (pageName == "declenchementPage") {
        rotationDirection = 9;
    }

    for (article of articles) {
        article.scrollTop = 0;
    }

}

// =============== MENU AND SUBMENUS ===============

function openSubmenu(menuName) {
    for (menuItem of menuItems) {
        if (menuItem.id == menuName + "MenuItem") {
            menuItem.classList.add("selected");
        }
        else {
            console.log("hidding submenu", menuItem.id);
            menuItem.classList.remove("selected");
        }
    }

    for (submenu of submenus) {
        if (submenu.id == menuName + "Submenu") {
            submenu.style.visibility = "visible";
        }
        else {
            console.log("hidding submenu", submenu.id);
            submenu.style.visibility = "hidden";
        }
    }

}
// ===================== FULL PAGE IMAGE ==================
elementWithFullScreenImages = [toursArticleElement]

for (elt of elementWithFullScreenImages) {
    elt.addEventListener("click", (ev) => {
        if (ev.target.tagName == "IMG") {
            if (ev.target.src.includes("/scenes/")) {
                if (ev.target.parentElement.tagName == "FIGURE") {
                    caption = ev.target.parentElement.getElementsByTagName("figcaption")[0];
                    console.log("caption", caption);
                    showFullImage(ev.target.src, caption.innerHTML);
                } else {
                    showFullImage(ev.target.src)
                }
            }
        };
    })
}

function showFullImage(imageSrc, caption = "") {
    document.getElementById("fullScreenImageId").firstElementChild.src = imageSrc;
    document.getElementById("fullScreenImageId").lastElementChild.innerHTML = caption;
    showFullScreenImage();
}

function showFullScreenImage() {
    overlayArticleBlur.style.display = "";
    document.getElementById("fullScreenImageId").style.display = "";
}

function closeFullScreenImage() {
    overlayArticleBlur.style.display = "none";
    document.getElementById("fullScreenImageId").style.display = "none";
}


// // ============ TOUCHSCREEN TOOLTIPS ==============

// //example tooltip : <p>This is a test for <span class="tooltip-text" title="This is an example tooltip">tooltips</span> !</p>
// function addTouchTooltips(article) {
//     let tooltipSpans = article.getElementsByClassName("tooltip-text");
//     for (span of tooltipSpans) {
//         span.setAttribute('data-tooltip', span.title);
//         span.removeAttribute('title');

//         span.addEventListener("click", (event) => {
//             { tooltipMouseOver(event.target) };
//             setDisapearTimeout(event.target);
//         });

//         // Mouse interaction !
//         /*span.addEventListener("mouseover", (event) => {tooltipMouseOver(event.target)});
//         span.addEventListener("mouseout", (event) => {
//             console.log("MOUSE OUT");
//             console.log(span);
//             if (span.nextElementSibling && span.nextElementSibling.classList.contains("tooltip")) {
//                 span.nextElementSibling.remove();
//             }
//         });*/
//     }
//     return (article);
// };


// function removeAllTooltips() {
//     let tooltipSpans = document.getElementsByClassName("tooltip-text");
//     clearTimeout(tooltipsTimeout);
//     for (s of tooltipSpans) {
//         const next = s.nextElementSibling
//         if (next && next.classList.contains('tooltip')) {
//             next.remove()
//         }
//     }
// }

// // Handling user clicking multiple times on a tooltip span
// let tooltipsTimeout;
// function setDisapearTimeout(target) {
//     clearTimeout(tooltipsTimeout);
//     tooltipsTimeout = setTimeout(() => {
//         target.nextElementSibling.animate(
//             [{ opacity: 1 },
//             { opacity: 0 }],
//             { duration: 500 }
//         );
//         console.log("target.nextElementSibling.style", target.nextElementSibling.style.cssText);
//         target.nextElementSibling.style = target.nextElementSibling.style.cssText + " opacity: 0;";
//     }, 4000)
// }


// function tooltipMouseOver(span) {
//     removeAllTooltips()

//     tooltip = document.createElement("span");
//     tooltip.classList.add("tooltip");
//     tooltip.appendChild(document.createTextNode(span.dataset.tooltip));
//     span.insertAdjacentElement("afterend", tooltip);

//     // tooltip position 
//     const rect = span.getBoundingClientRect();
//     const left = rect.left + rect.width + 4;
//     const top = rect.top - 4;
//     span.nextElementSibling.style = "left: " + left + "px; top: " + top + "px;";
// }


// // ============ Add Biblio Links ==============
// //<span class="biography-link" data-target="dEstreesMiniportraitID">cardinal d'Estr&eacute;e</span>
// function addBiblioLinks(article) {
//     let bioLinks = article.getElementsByClassName("biography-link");
//     for (linkSpan of bioLinks) {
//         linkSpan.addEventListener("click", (event) => {
//             if (currentPage != "portraitsPage") {
//                 pageStack.push(currentPage);
//             }
//             console.log("show portrait ", event.target.dataset.target);
//             showPortraitPage(event.target.dataset.target, true);
//         });
//     }
// }

// ============ Inverting Rotation ============
let rotationDirection = 9;
function invertRotation() {
    if (rotationDirection == 9) {
        rotationDirection = 10;
    } else {
        rotationDirection = 9
    }
    voyagerElement.setTourStep(0, rotationDirection, false);
}

// ============ Step clicks ============
/* for (element of tourStepsElements) {
    element.addEventListener("click", (event) => {
        event.target.classList.remove("unselectedStep");
        event.target.classList.add("selectedStep");
        for (e of tourStepsElements) {
            if (e != event.target) {
                if (e.classList.contains("selectedStep")) {
                    e.classList.remove("selectedStep");
                    e.classList.add("unselectedStep");
                } else {
                    e.classList.remove("unselectedStep");
                }
                if (e.id == "alimentationStepButtonId") {
                    console.log("clearing timout");
                    clearTimeout(stepTimeoutID);
                }
            }
        }
    })
}
 */
function updateArticleContainer(id) {
    console.log("UPDATE ARTICLE : ", id);
    console.log(toursArticleContainerElement);
    toursArticleContainerElement.scrollTop = 0;
    if (id) {
        setArticleContent(toursArticleElement, `new-article-${id}`);
        toursArticleContainerElement.style.display = "";
    } else {
        toursArticleElement.innerHTML = "";
        toursArticleContainerElement.style.display = "none";
    }
}

voyagerElement.application.documentProvider.activeComponent.setup.reader.ins.articleId.on("value", () => updateArticleContainer(voyagerElement.application.documentProvider.activeComponent.setup.reader.ins.articleId.value), this);

