#include html.js

(() => {
    const perfs = <div class="msz-perfs"/>;
    perfs.ondblclick = () => {
        perfs.classList.toggle('msz-perfs-right');
    };

    const appendReal = elem => {
        $appendChild(perfs, elem);
    };

    let append = elem => {
        append = appendReal;
        $appendChild(document.body, perfs);
        appendReal(elem);
    };

    (new PerformanceObserver(list => {
        for(const entry of list.getEntries()) {
            if(entry.serverTiming.length < 1)
                break;

            const url = new URL(entry.name);

            let total = 0;
            let queries = -1;
            const timings = <table class="msz-perf-timings"/>;
            for(const timing of entry.serverTiming) {
                if(timing.name === 'msz-queries') {
                    queries = Math.ceil(timing.duration);
                    continue;
                }

                total += timing.duration;
                $appendChild(timings, <tr class="msz-perf-timing">
                    <td class="msz-perf-timing-name">{timing.name}</td>
                    <td class="msz-perf-timing-comment">{decodeURIComponent(timing.description)}</td>
                    <td class="msz-perf-timing-duration">
                        <span class="msz-perf-number">{timing.duration}</span>
                        <span class="msz-perf-unit">ms</span>
                    </td>
                </tr>);
            }

            append(<div class="msz-perf">
                <div class="msz-perf-header">
                    <div class={`msz-perf-type msz-perf-type-${entry instanceof PerformanceNavigationTiming ? 'navigation' : 'other'}`}>
                        {entry instanceof PerformanceNavigationTiming ? entry.type : (
                            entry.initiatorType === 'xmlhttprequest' ? 'xhr' : entry.initiatorType
                        )}
                    </div>
                    <div class="msz-perf-target">
                        {url.host !== location.host ? <div class="msz-perf-target-host">{url.host}</div> : null}
                        <div class="msz-perf-target-path">{url.pathname}</div>
                        {url.search !== '' ? <div class="msz-perf-target-query">{url.search}</div> : null}
                    </div>
                    {queries > 0 ? <div class="msz-perf-total">
                        <span class="msz-perf-number">{queries}</span>
                        {' '}
                        <span class="msz-perf-unit">{queries === 1 ? 'query' : 'queries'}</span>
                    </div> : null}
                    <div class="msz-perf-total">
                        <span class="msz-perf-number">{total.toFixed(5)}</span>
                        <span class="msz-perf-unit">ms</span>
                    </div>
                </div>
                {timings}
            </div>);
        }
    })).observe({ entryTypes: ['navigation', 'resource'] });
})();
