{{{ICON_JS}}}

let {{JS_PREFIX}}_app_details = false;
let {{JS_PREFIX}}_last_stats = null;
let {{JS_PREFIX}}_app_stats_last_change = 0;
const {{JS_PREFIX}}_app_stats_timeout = 35000;

function {{JS_PREFIX}}_hide_app_details() {
    const detailsDivId = '{{JS_PREFIX}}_detailsDiv';
    const detailsDiv = document.getElementById(detailsDivId);
    {{JS_PREFIX}}_app_details = false;
    if (detailsDiv != null) {
        detailsDiv.style.display = 'none';
        while (detailsDiv.firstChild) {
            detailsDiv.removeChild(detailsDiv.lastChild);
        }
    }
}

function {{JS_PREFIX}}_show_app_details(ev) {
    const detailsDivId = '{{JS_PREFIX}}_detailsDiv';
    let detailsDiv = document.getElementById(detailsDivId);
    {{JS_PREFIX}}_app_details = true;
    {{JS_PREFIX}}_app_refresh(function () {
        if ({{JS_PREFIX}}_last_stats != null) {
            if (detailsDiv === null) {
                detailsDiv = {{PAGE_PREFIX}}_createDetailsDiv(detailsDivId);
                document.getElementsByTagName('body')[0].appendChild(detailsDiv);
            }
            while (detailsDiv.firstChild) {
                detailsDiv.removeChild(detailsDiv.lastChild);
            }
            detailsDiv.style.display = 'block';

            const titleSpan = {{JS_PREFIX}}_app_title_span('BlockParty!');
            const topButtons = document.createElement('span');
            const topCloseButton = {{JS_PREFIX}}_create_button('web_close', 'close', function (e) {
                e.stopPropagation();
                e.preventDefault();
                {{JS_PREFIX}}_hide_app_details();
                return false;
            });
            topButtons.style.float = 'right';
            topButtons.appendChild(topCloseButton);
            titleSpan.appendChild(topButtons);
            detailsDiv.appendChild(titleSpan);
            detailsDiv.appendChild(document.createElement('hr'));

            // add rows for blocked stuff...
            const adsAndTrackersHeader = {{JS_PREFIX}}_app_header('web_adsAndTrackers', 'Blocked Ads/Trackers');
            detailsDiv.appendChild(adsAndTrackersHeader);
            if ({{JS_PREFIX}}_last_stats.blocks.length === 0) {
                const emptyLabel = {{PAGE_PREFIX}}_msg_or_default({{JS_PREFIX}}_messages, 'web_noAdsOrTrackers', '(no blocks)');
                detailsDiv.appendChild(document.createElement('br'));
                detailsDiv.appendChild(document.createTextNode(emptyLabel));
            } else {
                for (let i = 0; i < {{JS_PREFIX}}_last_stats.blocks.length; i++) {
                    const entry = {{JS_PREFIX}}_last_stats.blocks[i];
                    const entryDiv = {{JS_PREFIX}}_app_entry_div();
                    const entryText = document.createTextNode(entry.fqdn + ': ' + entry.count);
                    entryDiv.appendChild(entryText);
                    detailsDiv.appendChild(entryDiv);
                }
            }
            detailsDiv.appendChild(document.createElement('hr'));
            const domain = {{PAGE_PREFIX}}_get_fqdn_tld();
            const hideStatsButton = {{JS_PREFIX}}_create_button('web_hideStats', 'Hide BlockParty for ', function (e) {
                // write appdata
                const hide_show_stats_url = '/__bubble/api/filter/data/{{BUBBLE_DATA_ID}}/write';
                const requestOptions = {
                    method: 'POST',
                    body: JSON.stringify({key: 'showStats_'+domain, data: 'false'})
                };
                fetch(hide_show_stats_url, requestOptions)
                    .then(() => window.location.reload());
                return false;
            }, label => label + domain);

            detailsDiv.appendChild(hideStatsButton);
            detailsDiv.appendChild(document.createElement('hr'));
            const closeButton = {{JS_PREFIX}}_create_button('web_close', 'close', function (e) {
                e.stopPropagation();
                e.preventDefault();
                {{JS_PREFIX}}_hide_app_details();
                return false;
            });
            detailsDiv.appendChild(closeButton);
        }
    });
}

const {{JS_PREFIX}}_app_refresh = function (displayFunc) {
    const requestOptions = { method: 'GET' };
    const block_stats_url = '/__bubble/api/filter/status/{{BUBBLE_REQUEST_ID}}';
    fetch(block_stats_url, requestOptions)
        .then(resp => {
            try {
                return resp.json();
            } catch (error) {
                console.log('cancelling window.interval, response not json: '+JSON.stringify(resp));
                window.clearInterval({{JS_PREFIX}}_app_refresh_interval);
            }
        })
        .then(data => {
            // console.log('stats = '+JSON.stringify(data));
            let icon = null;
            if (typeof data.total !== 'undefined') {
                if (JSON.stringify(data) !== JSON.stringify({{JS_PREFIX}}_last_stats)) {
                    {{JS_PREFIX}}_last_stats = data;
                    {{JS_PREFIX}}_app_stats_last_change = Date.now();
                    if (data.total === 0) {
                        icon = 'icon-green';
                    } else if (data.total < 5) {
                        icon = 'icon-yellow';
                    } else {
                        icon = 'icon-red';
                        if ({{JS_PREFIX}}_app_refresh_interval !== null) {
                            console.log('cancelling window.interval, red status');
                            window.clearInterval({{JS_PREFIX}}_app_refresh_interval);
                            {{JS_PREFIX}}_app_refresh_interval = null;
                        }
                    }
                    {{JS_PREFIX}}_app.icon = icon;
                    {{PAGE_PREFIX}}_setAppIconImg({{JS_PREFIX}}_app);

                } else if ({{JS_PREFIX}}_app_refresh_interval !== null && Date.now() - {{JS_PREFIX}}_app_stats_last_change > {{JS_PREFIX}}_app_stats_timeout) {
                    console.log('cancelling window.interval, stats unchanged for a while');
                    window.clearInterval({{JS_PREFIX}}_app_refresh_interval);
                    {{JS_PREFIX}}_app_refresh_interval = null;
                }
                if (typeof displayFunc === 'function') {
                    displayFunc();
                }
            }
        }).catch((error) => {
            if ({{JS_PREFIX}}_app_refresh_interval !== null) {
                console.log('cancelling window.interval, due to error: ' + error);
                window.clearInterval({{JS_PREFIX}}_app_refresh_interval);
                {{JS_PREFIX}}_app_refresh_interval = null;
            } else {
                console.log('error: ' + error);
            }
    });
}

let {{JS_PREFIX}}_app_refresh_interval = null;
const {{JS_PREFIX}}_app = {
    jsPrefix: '{{JS_PREFIX}}',
    app: '{{BUBBLE_APP_NAME}}',
    link: {{JS_PREFIX}}_show_app_details,
    icon: 'icon-gray',
    onReady: function () {
        {{JS_PREFIX}}_load_messages('web_', function (messages) {
                {{JS_PREFIX}}_messages = messages;
        });
        document.onkeydown = function(e) {
            e = e || window.event;
            let isEscape = false;
            if ("key" in e) {
                isEscape = (e.key === "Escape" || e.key === "Esc");
            } else {
                isEscape = (e.keyCode === 27);
            }
            if (isEscape) {{JS_PREFIX}}_hide_app_details();
        };
        {{JS_PREFIX}}_app_refresh_interval = window.setInterval({{JS_PREFIX}}_app_refresh, 5000);
    }
};

{{PAGE_PREFIX}}_addBubbleApp({{JS_PREFIX}}_app);
