export class ScrollTool {
    ////////////////////////////////////////////////////////////////
    // Static Methods
    ////////////////////////////////////////////////////////////////
    /**
     * Scroll smoothly to the desired given element
     * @param destID
     * @param lastClick
     * @param threshold
     * @param delay
     * @param duration
     */
    static scrollSmoothlyTo(destID, lastClick, threshold = 0, delay = 501, duration = 500) {
        /* To prevent "bounce" */
        /* https://stackoverflow.com/a/28610565/3405291 */
        if (lastClick >= (Date.now() - delay)) {
            return;
        }
        // Retrieve the HTML object according to the id
        const dest = document.getElementById(destID);
        const to = dest.offsetTop;
        // Stop if the scroll is already to the position
        if ((document.body.scrollTop || document.documentElement.scrollTop || 0) == to) {
            return;
        }
        const initialDiff = to - (document.body.scrollTop || document.documentElement.scrollTop || 0);
        const scrollStep = Math.PI / (duration / 10);
        let count = 0;
        let currPos;
        let scrollTop;
        let similarScrollTopCount = 0; // Use to measure whether the position is stable or not
        let lastScrollTop;
        const start = window.pageYOffset;
        const scrollInterval = setInterval(() => {
            // Measures the difference between the current scroll and the targeted one to achieve
            // Continues until the position is perfectly achieved OR a stable position is achieved
            scrollTop = (document.body.scrollTop || document.documentElement.scrollTop || 0);
            if (Math.abs(scrollTop - to) > threshold && similarScrollTopCount < 3) {
                if (scrollTop === lastScrollTop) {
                    ++similarScrollTopCount;
                }
                lastScrollTop = scrollTop;
                count++;
                currPos = start + initialDiff * (.5 - .5 * Math.cos(count * scrollStep));
                /* https://stackoverflow.com/q/28633221/3405291 */
                /* To support both Chromium-based and Firefox */
                document.body.scrollTop = currPos;
                document.documentElement.scrollTop = currPos;
            }
            else {
                clearInterval(scrollInterval);
            }
        }, 10);
    }
}
