/* eslint no-var: "error" */
/* eslint no-unused-vars: "off" */
/* eslint linebreak-style: "off" */
/* eslint no-trailing-spaces: "off" */
/* eslint capitalized-comments: "off" */
/* eslint-env es6 */

import Debugger from './debugger';
const debug = new Debugger("browserbuttonevents");

/**
 * 
 * @param {function} backwardCB 
 * @param {function} forwardCB 
 * @param {function} reloadCB 
 */
export function addBrowserButtonEvent(backwardCB, forwardCB = null, reloadCB = null) {
    debug.log("Registering navigation events", backwardCB, forwardCB, reloadCB);
    const reorient = (e) => { // After travelling in the history stack
        const positionLastShown = Number( // If none, then zero
          sessionStorage.getItem('positionLastShown'));
        // debug.log("Popstate event",e,positionLastShown,history);
        let position = history.state; // Absolute position in stack
        if (position === null) { // Meaning a new entry on the stack
            position = positionLastShown + 1; // Top of stack
    
            // (1) Stamp the entry with its own position in the stack
            history.replaceState(position, /* no title */''); 
        }
    
        // (2) Keep track of the last position shown
        sessionStorage.setItem('positionLastShown', String(position));
    
        // (3) Discover the direction of travel by comparing the two
        const direction = Math.sign(position - positionLastShown);
        debug.log('Travel direction is ' + direction); 
          // One of backward (-1), reload (0) and forward (1)
        if (direction == -1 && backwardCB) {
            backwardCB();
        }
        if (direction == 1 && forwardCB) {
            forwardCB();
        }
        if (direction == 0 && reloadCB) {
            reloadCB();
        }
    };
    // addEventListener( 'pageshow', reorient );
    addEventListener('popstate', reorient); // Travel in same page
}