<%- await include('parts/header.ejs', locals) %>

<link href="<%= resourcePath %>xtermjs/xterm.min.css?txVer=<%= txAdminVersion %>" rel="stylesheet">
<style>
    .pre-log-content{
        height: calc(100vh - 252px);
        margin-bottom: 0;
    }
    .nui-height{
        height: calc(100vh - 152px);
    }
</style>

<div>
    <ul class="nav nav-pills nav-tabs justify-content-center mb-2">
        <li class="nav-item"><a class="nav-link active" data-toggle="tab" href="#nav-console"
            role="tab" aria-controls="nav-console" aria-selected="true">Console Logs</a></li>
        <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#nav-actions"
            role="tab" aria-controls="nav-actions" aria-selected="true" onclick="doScroll('actionsLog');">Actions Logs</a></li>
    </ul>
</div>
<div class="card border-primary">
    <div class="card-body">
        <div class="tab-content <%= isWebInterface ? '' : 'nui-height' %>" id="nav-tabContent">
            <div class="tab-pane fade active show" id="nav-console" role="tabpanel">
                <div id="terminal" class="thin-scrollx pre-log-content  <%= (isWebInterface ? '' : 'nui-height') %>"></div>
            </div>
            <div class="tab-pane fade" id="nav-actions" role="tabpanel">
                <pre id="actionsLog" class="thin-scroll pre-log-content"><%- actionLog %></pre>
            </div>
        </div>
    </div>
</div>


<%- await include('parts/footer.ejs', locals) %>
<script src="<%= resourcePath %>xtermjs/xterm.min.js?txVer=<%= txAdminVersion %>"></script>
<script src="<%= resourcePath %>xtermjs/xterm-addon-fit.min.js?txVer=<%= txAdminVersion %>"></script>
<script src="<%= resourcePath %>xtermjs/xterm-addon-search.js?txVer=<%= txAdminVersion %>"></script>
<script src="<%= resourcePath %>xtermjs/xterm-addon-search-bar.min.js?txVer=<%= txAdminVersion %>"></script>
<script>
    // From MDN - atob doesn't support utf8 strings
    // https://developer.mozilla.org/en-US/docs/Glossary/Base64
    function b64_to_utf8(b64) {
        return decodeURIComponent(escape(atob(b64)));
    }

    //Injecting the console content here as base64
    const logData = b64_to_utf8(`<%= (Buffer.from(consoleLog).toString('base64')) %>`);

    //ANSI-UP theme
    const baseTheme = {
        background: '#29292A', //to match web 
        foreground: '#F8F8F8',
        selection: '#5DA5D533',
        black: '#000000',
        brightBlack: '#555555',
        red: '#D62341',
        brightRed: '#FF5370',
        green: '#9ECE58',
        brightGreen: '#C3E88D',
        yellow: '#FAED70',
        brightYellow: '#FFCB6B',
        blue: '#396FE2',
        brightBlue: '#82AAFF',
        magenta: '#BB80B3',
        brightMagenta: '#C792EA',
        cyan: '#2DDAFD',
        brightCyan: '#89DDFF',
        white: '#D0D0D0',
        brightWhite: '#FFFFFF'
    };
    const term = new Terminal({
        theme: baseTheme,
        fontFamily: "Cascadia Mono, monospace",
        fontWeight: "300",
        cursorStyle: "bar",
        drawBoldTextInBrightColors: false,
        disableStdin: true,
        allowTransparency: true,
        convertEol: true,
        cursorBlink: true,
    });

    //Instantiating and adding addons
    const fitAddon = new FitAddon.FitAddon();
    const searchAddon = new SearchAddon.SearchAddon();
    const searchBar = new SearchBarAddon.SearchBarAddon({ searchAddon });
    term.loadAddon(fitAddon);
    term.loadAddon(searchAddon);
    term.loadAddon(searchBar);

    //Attaching terminal
    const terminalElement = document.getElementById('terminal');
    term.open(terminalElement);
    fitAddon.fit();
    term.write(logData);

    term.attachCustomKeyEventHandler((event) => {
        if(event.code === 'F5'){
            window.location.reload(true);
        } else if(event.code === 'KeyC' && (event.ctrlKey || event.metaKey)){
            document.execCommand('copy');
            term.clearSelection();
        } else if(event.code === 'Escape'){
            searchBar.hidden();
        } else if(event.code === 'KeyF' && (event.ctrlKey || event.metaKey)){
            searchBar.show();
            event.preventDefault();
        }
    });

    //Debounced resizer
    let resizeTimeout;
    window.addEventListener("resize", () => {
        clearTimeout(resizeTimeout);
        terminalElement.style.opacity = 0.5;
        resizeTimeout = setTimeout(() => {
            terminalElement.style.opacity = 1;
            fitAddon.fit();
            console.log('resized');
        }, 150);
    });

    function doScroll(target){
        setTimeout(() => {
            $("#"+target).scrollTop($("#"+target)[0].scrollHeight);
        }, 250);
    }
</script>
