
function resetQuery() {
    let urlComponents = location.href.match(/^([^\?#]+)(\?[^#]+)?(#.+)?$/);

    if (urlComponents[2]) {
        urlComponents[2] = urlComponents[2]
            .replace(/[\?&]action\.[\w_\-]+=[^&#]*/g, '');

        if (urlComponents[2] && urlComponents[2].indexOf('?') !== 0)
            urlComponents[2] = '?' + urlComponents[2];
    }

    history.pushState(null, null, urlComponents.slice(1).join(''));
}

function render(element) {
    if (!element || element.dataset.activated)
        return;

    resetQuery();

    element.querySelector('[data-id="close"]').addEventListener('click', event => {
        event.preventDefault();
        element.remove();
    });

    element.querySelector('[data-id="copy"]').addEventListener('click', () => {
        let container = element.querySelector('[data-id="body"]');

        container.setAttribute('contenteditable', '');
        container.focus();

        document.execCommand('selectAll');
        document.execCommand('copy');

        container.removeAttribute('contenteditable');
        if (document.getSelection) document.getSelection().removeAllRanges();
    });

    element.dataset.activated = true;
}

function renderAll() {
    Array.from(document.querySelectorAll('[data-element="notification"]'))
        .forEach(render);
}

renderAll();

export default { render };