(() => {
    /**
     * Check and set a global guard variable.
     * If this content script is injected into the same page again,
     * it will do nothing next time.
     */
    if (window.hasRun) {
      return;
    }
    window.hasRun = true;

    let pad_root = 'https://cached-pad.osp.kitchen/';
    let default_pad = 'https://pad.constantvzw.org/p/declarations-scratch';

    function fetch_request(url, callback){
        // fetching the pad
        let new_url = pad_root + '/p/' + url.split('/p/')[1]

        fetch(`${url}/export/txt`, {
            'method': 'GET',
            'mode': 'cors',
        })
        .then(response => response.text() )
        .then(css => inject_css(css) );
    }

    function inject_css(css){

        console.log('pad loaded!');

        // remove previously imported pad as style
        let etherstyle = document.getElementById('etherstyle');
        if (etherstyle) { etherstyle.remove(); }

        // import new pad as style
        let el = document.createElement('style');
        el.id = "etherstyle";
        el.type = 'text/css';
        el.innerText = css;
        document.head.appendChild(el);

        let everything = document.querySelectorAll('*');
        for(thing of everything){
            thing.setAttribute('tabindex', '0');
        }
    };

    function load_pad(pad){
        fetch_request(pad, inject_css);
    }

    // --- storage
    browser.storage.local.get('etherpad').then(function(result){
        if(result.etherpad){
            etherpad = result.etherpad;
        } else{
            etherpad = default_pad
        }
    }).then(function(){
        console.log('loading pad', etherpad);
        load_pad(etherpad);
    });

    // --- update
    browser.runtime.onMessage.addListener((message) => {
        if (message.command === "etherpadchange") {
            
            new_pad = message.url;
            console.log("changing etherpad", new_pad);
            browser.storage.local.set({ "etherpad": new_pad });
            load_pad(new_pad);
        }
    });

})();