import navigatorUtil from 'internal/util/navigator';

import Widget from '../widget/widget';

export default class History extends Widget {

    constructor(localWindow) {
        super();
        this._localWindow = localWindow || window;
        this.titleSuffix = '';
        this._init();
    }

    pushState(state, title, url) {
        this._localWindow.history.pushState(state, title || '', url || '');
        this._maybeSetTitle(title);
        this.trigger('changestate', { state: state });
    }

    replaceState(state, title, url) {
        this._localWindow.history.replaceState(state, title || '', url || '');
        this._maybeSetTitle(title);
        this.trigger('changestate', { state: state });
    }

    state() {
        return this._localWindow.history.state;
    }

    initialState(state) {
        return this._localWindow.history.replaceState(state, '', this._localWindow.location.href);
    }

    setTitleSuffix(suffix) {
        this.titleSuffix = suffix || '';
    }

    _init() {
        //Safari fires an event on every page load. We want to swallow this event.
        let skipNextPop = navigatorUtil.isSafari();
        const listener = e => {
            //The initial event in Safari has event.state === null so if the first event has some state
            //then let it through.
            if (e && (!skipNextPop || e.state !== null)) {
                this.trigger('popstate', e);
                this.trigger('changestate', e);
            }

            if (skipNextPop) {
                skipNextPop = false;
            }
        };
        this._localWindow.addEventListener('popstate', listener);

        this._addDestroyable(() => {
            this._localWindow.removeEventListener('popstate', listener);
        });
    }

    _maybeSetTitle(title) {
        if (title) {
            this._localWindow.document.title = title + this.titleSuffix;
        }
    }
}
