

import setTimeout from '@schematize/refs/js/setTimeout.mjs';

import w from '@schematize/refs/browser/window.mjs';
import h from '@schematize/refs/browser/window.history.mjs';

import {
  addEventListener,
  dispatchEvent,
} from './eventTarget.mjs';

const S_statechange = `statechange`;
// const SYMBOL_toStringTag = Symbol.toStringTag;

//------------------------------------------------------------------------------
// history
//------------------------------------------------------------------------------
// back
export const back = () => h.back();
// forward
export const forward = () => h.forward();
// go
export const go = (index) => h.go(index);

// PopStateEvent
//------------------------------------------------------------------------------
const PopStateEvent = w.PopStateEvent;
// StateChangeEvent
class StateChangeEvent extends PopStateEvent {
  // get [SYMBOL_toStringTag]() {
  //   return 'StateChangeEvent';
  // }
}
// fire our custom event when something happens
addEventListener(w, `popstate`,
  (ev) => setTimeout(
    () => dispatchEvent(w, new StateChangeEvent(S_statechange, ev)),
    0
  )
);

// PushStateEvent
//------------------------------------------------------------------------------
class PushStateEvent extends PopStateEvent {
  // get [SYMBOL_toStringTag]() {
  //   return 'PushStateEvent';
  // }
}
// pushState
export const pushState = (state, title, url) => {
  let options = {
    state: state
  };
  // call native
  h.pushState(state, title, url);
  // dispatch custom
  dispatchEvent(w, new PushStateEvent(`pushstate`, options));
  // dispatch custom
  dispatchEvent(w, new StateChangeEvent(S_statechange, options));
};

// ReplaceStateEvent
//------------------------------------------------------------------------------
class ReplaceStateEvent extends PopStateEvent {
  // get [SYMBOL_toStringTag]() {
  //   return 'ReplaceStateEvent';
  // }
}
// replaceState
export const replaceState = (state, title, url) => {
  let options = {
    state: state
  };
  // call native
  h.replaceState(state, title, url);
  // dispatch custom
  dispatchEvent(w, new ReplaceStateEvent(`replacestate`, options));
  // dispatch custom
  dispatchEvent(w, new StateChangeEvent(S_statechange, options));
};