{{@include("header", it)/}}

<style>
    .pInfoCallout{
        min-width: 180px !important;
    }
    .pInfoCallout .c-callout{
        padding-bottom: 2px;
    }
    .pInfoCallout small{
        letter-spacing: .04em;
    }
    .txInlineBtn{
        border-radius: .25rem;
        line-height: 1;
        text-align: center;
        white-space: nowrap;
        letter-spacing: 0.1rem;
    }
    .txActionsBtn{
        font-size: 85%;
        font-weight: 700;
        padding: .25rem !important;
        vertical-align: top;
    }
    .txWhitelistBtn{
        font-size: 65%;
        padding: .2rem !important;
        vertical-align: text-top;
    }

    .logEntry{
        color: #768192;
        padding: .15rem 0.55rem;
        margin-bottom: 4px !important;
    }
    .logEntry:hover{
        background-color: #ebedef;
    }
    .logEntry:hover button{
        color: #fff;
        background-color: #636f83;
    }
    .logEntry small{
        margin-top: .25em;
    }
    .logEntryClickable{
        cursor: pointer;
    }

    .searchTab{
        min-height: 64px;
    }

    .c-callout{
        margin: 0;
    }
</style>


<!-- Callouts -->
<div class="row justify-content-center">
    <div class="row col-xl-10 p-0 pb-3 justify-content-center">
        <div class="col-2 pInfoCallout">
            <div class="c-callout c-callout-info">
                <small class="text-muted">Total Players</small><br>
                <strong class="h4">{{it.stats.players}}</strong>
            </div>
        </div>
        <div class="col-2 pInfoCallout">
            <div class="c-callout c-callout-info">
                <small class="text-muted">Total Playtime</small><br>
                <strong class="h4">{{it.stats.playTime}}</strong>
            </div>
        </div>
        <!-- <div class="col-2 pInfoCallout">
            <div class="c-callout c-callout-success">
                <small class="text-muted">New Players This Week</small><br>
                <strong class="h4">9,123</strong>
            </div>
        </div>
        <div class="col-2 pInfoCallout">
            <div class="c-callout c-callout-success">
                <small class="text-muted">Playtime This Week</small><br>
                <strong class="h4">9,123</strong>
            </div>
        </div> -->
        <div class="col-2 pInfoCallout">
            <div class="c-callout c-callout-success">
                <small class="text-muted">Whitelists</small><br>
                <strong class="h4">{{it.stats.whitelists}}</strong>
            </div>
        </div>
        <div class="col-2 pInfoCallout">
            <div class="c-callout c-callout-warning">
                <small class="text-muted">Warns</small><br>
                <strong class="h4">{{it.stats.warns}}</strong>
            </div>
        </div>
        <div class="col-2 pInfoCallout">
            <div class="c-callout c-callout-danger">
                <small class="text-muted">Bans</small><br>
                <strong class="h4">{{it.stats.bans}}</strong>
            </div>
        </div>
    </div>
</div>


<!-- Main info -->
<div class="row justify-content-center">

    <div class="col-md-10 col-lg-8 col-xl-5 mw-col6">

        <!-- Whitelist -->
        <div class="card card-accent-success">
            <div class="card-header font-weight-bold">
                <h5 class="float-left mb-0" style="padding-top: .175em;">
                    Last {{it.queryLimits.whitelist}} Whitelist requests:
                </h5>
                {{@if(!it.disableWhitelist)}}
                    <button class="btn btn-sm btn-success float-right" type="button" 
                        onclick="whitelistID(null)" {{it.permsDisable.whitelist|isDisabled}}>
                        <i class="icon-check"></i> Whitelist ID / License
                    </button>
                {{/if}}
            </div>
            <div class="card-body text-center">
                {{@if(it.disableWhitelist)}}
                    <div class="text-center">
                        <h3 class="mx-auto pt-3 text-danger">Whitelist checking disabled</h3>
                    </div>
                {{#else}}
                    {{@if(it.lastWhitelistBlocks.length == 0)}}
                        <h3 class="mx-auto text-secondary">No pending whitelist requests</h3>
                    {{#else}}
                        <table class="table table-responsive-sm table-borderless table-striped table-sm text-left">
                            <thead>
                                <tr>
                                    <th>Actions</th>
                                    <th>Time</th>
                                    <th>ID</th>
                                    <th>Name</th>
                                </tr>
                            </thead>
                            <tbody>
                                {{@each(it.lastWhitelistBlocks) => wlReq}}
                                <tr>
                                    <td>
                                        {{@if(it.permsDisable.whitelist)}}
                                            <button class="btn btn-secondary txInlineBtn txWhitelistBtn disabled"
                                                disabled>ACCEPT</button>
                                        {{#else}}
                                            <button onclick="whitelistID('{{wlReq.id}}')" 
                                                class="btn btn-primary txInlineBtn txWhitelistBtn">ACCEPT</button>
                                        {{/if}}
                                    </td>
                                    <td>{{wlReq.time}}</td>
                                    <td class="text-monospace">{{wlReq.id}}</td>
                                    <td class="text-truncate">{{wlReq.name}}</td>
                                </tr>
                                {{/each}}
                            </tbody>
                        </table>
                    {{/if}}
                {{/if}}
            </div>
        </div>
        <!-- /Whitelist -->

        <!-- Ban ID -->
        <div class="card card-accent-danger">
            <div class="card-header font-weight-bold">Ban Identifiers:</div>
            <div class="card-body">
                {{@if(it.disableBans)}}
                    <div class="text-center">
                        <h3 class="mx-auto pt-3 text-danger">ban checking disabled</h3>
                    </div>
                {{#else}}
                    {{@if(it.permsDisable.ban)}}
                        <div class="text-center">
                            <h3 class="mx-auto pt-3 text-secondary">you can't ban people</h3>
                        </div>
                    {{#else}}
                        <div class="form-group row">
                            <label for="frmAddBan-identifiers" class="col-sm-3 col-form-label">
                                Identifier(s) <br>
                                <small class="text-danger">(required)</small>
                            </label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="frmAddBan-identifiers"
                                    placeholder="steam:101010101010101, license:d3832ddc9f845bf...">
                                <span class="form-text text-muted">
                                    Valid identifiers: <code>steam, license, xbl, live, discord, fivem</code>.
                                    You can insert multiple IDs separated by comma.
                                </span>
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="frmAddBan-reason" class="col-sm-3 col-form-label">
                                Reason <br>
                                <small class="text-danger">(required)</small>
                            </label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="frmAddBan-reason" maxlength="256"
                                    placeholder="doing bad things :(">
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="frmAddBan-durationSelect" class="col-sm-3 col-form-label">
                                Duration
                            </label>
                            <div class="col-sm-9">
                                <select class="form-control" id="frmAddBan-durationSelect">
                                    <option value="2 hours">2 hours</option>
                                    <option value="8 hours">8 hours</option>
                                    <option value="1 day">1 day</option>
                                    <option value="2 days">2 days</option>
                                    <option value="1 week">1 week</option>
                                    <option value="2 weeks">2 weeks</option>
                                    <option value="permanent" class="font-weight-bold text-danger" selected>permanent</option>
                                    <option value="custom" class="font-weight-bold">custom</option>
                                </select>
                                <div class="row mt-2">
                                    <div class="col-sm-3 pr-0">
                                        <input type="number" class="form-control" id="frmAddBan-durationMultiplier" 
                                            maxlength="3" placeholder="7" disabled>
                                    </div>
                                    <div class="col-sm-9 pl-2">
                                        <select class="form-control" id="frmAddBan-durationUnit" disabled>
                                            <option value="hours">hours</option>
                                            <option value="days">days</option>
                                            <option value="weeks" selected>weeks</option>
                                            <option value="months">months</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="text-center mt-4">
                            <button class="btn btn-sm btn-danger" type="submit" id="frmAddBan-button">
                                <i class="icons cui-check"></i> Ban Identifiers
                            </button>
                        </div>
                    {{/if}}
                {{/if}}
            </div>
        </div>
        <!-- /Ban ID -->

        <div class="text-center">
            <small class="text-muted">{{it.message|safe}}</small>
        </div>

    </div>



    <div class="col-md-10 col-lg-8 col-xl-5 mw-col8">
        
        <!-- Search + List Card -->
        <div class="card">
            <div class="card-header card-accent-info">
                <!-- <h5 class="float-left mb-0" style="padding-top: .175em;">
                    Database Actions (bans/warns/whitelists)
                </h5> -->
                <!-- FIXME: currently disabled -->
                <ul class="nav nav-pills card-header-pills">
                    <div class="form-group row mb-0 mr-auto">
                        <div class="col-md-12">
                            <div class="input-group">
                                <input class="form-control" id="dbSearch-input" type="text"
                                    placeholder="name, license, IDs">
                                <span class="input-group-append">
                                    <button class="btn btn-sm btn-secondary" type="button" id="dbSearch-button">
                                        <svg class="c-icon">
                                            <use xlink:href="img/coreui_icons.svg#cil-magnifying-glass"></use>
                                        </svg> Search
                                    </button>
                                </span>
                            </div>
                        </div>
                    </div>
                    <li class="nav-item">
                        <a class="nav-link" id="dbPlayers-tab" data-toggle="pill" href="#dbPlayers-content" role="tab" 
                            aria-controls="dbPlayers-content" aria-selected="false"><i class="icon-user"></i> Players</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" id="dbActions-tab" data-toggle="pill" href="#dbActions-content" role="tab" 
                            aria-controls="dbActions-content" aria-selected="true"><i class="icon-notebook"></i> Actions</a>
                    </li>
                </ul>
            </div>
            <div class="card-body">
                <div class="tab-content">
                    <h5 class="text-center text-primary mb-2" id="dbSearch-message"></h5>
                    <div class="tab-pane fade" id="dbPlayers-content" role="tabpanel" aria-labelledby="dbPlayers-tab">
                        <div id="dbPlayers-tabSearch" class="searchTab d-none"></div>
                        <div id="dbPlayers-tabDefault">
                            <h5 class="card-title">Last {{it.queryLimits.players}} joined players</h5>
                            {{@if(it.lastPlayers.length == 0)}}
                                <div class="text-center">
                                    <h3 class="mx-auto pt-3 text-secondary">no players yet...</h3>
                                </div>
                            {{#else}}
                                <div class="list-group list-group-accent">
                                    {{@each(it.lastPlayers) => player}}
                                        <!-- FIXME: fix logEntryClickableX and onclickX-->
                                        <div class="list-group-item list-group-item-accent-{{player.color}} logEntry logEntryClickable">
                                            <div class="d-flex w-100 justify-content-between" onclick="showPlayer('{{player.license}}')"> 
                                                <strong>{{player.name}}</strong>
                                                <small>{{player.joined}}</small>
                                            </div>
                                        </div>
                                    {{/each}}
                                </div>
                            {{/if}}
                        </div>
                    </div>

                    <div class="tab-pane fade show active" id="dbActions-content" role="tabpanel" aria-labelledby="dbActions-tab">
                        <div id="dbActions-tabSearch" class="searchTab d-none"></div>
                        <div id="dbActions-tabDefault">
                            <h5 class="card-title">Last {{it.queryLimits.actions}} actions (bans/warns/whitelists):</h5> 
                            {{@if(it.lastActions.length == 0)}}
                                <div class="text-center">
                                    <h3 class="mx-auto pt-3 text-secondary">no actions yet...</h3>
                                </div>
                            {{#else}}
                                <div class="list-group list-group-accent">
                                    {{@each(it.lastActions) => action}}
                                        <div class="list-group-item list-group-item-accent-{{action.color}} logEntry">
                                            <div class="d-flex w-100 justify-content-between">
                                                <strong>{{action.message|safe}}</strong>
                                                <small class="text-right">
                                                    <span class="text-monospace font-weight-bold">({{action.id}})</span>
                                                    {{action.date}}
                                                    {{@if(!it.permsDisable.ban || !it.permsDisable.whitelist)}}
                                                        {{@if(
                                                            action.isRevoked ||
                                                            action.type == 'warn' ||
                                                            (action.type == 'ban' && it.permsDisable.ban) ||
                                                            (action.type == 'whitelist' && it.permsDisable.whitelist)
                                                        )}}
                                                            &nbsp;
                                                            <span class="badge badge-outline-light txInlineBtn txActionsBtn">REVOKE</span>
                                                        {{#else}}
                                                            &nbsp;
                                                            <button onclick="revokeAction('{{action.id}}')" 
                                                                class="btn btn-secondary txInlineBtn txActionsBtn">REVOKE</button>
                                                        {{/if}}
                                                    {{/if}}
                                                </small>
                                            </div>
                                            <span>{{action.reason|unnull}}</span>
                                            {{@if(action.footerNote)}}
                                                <small class="d-block">{{action.footerNote}}</small>
                                            {{/if}}
                                        </div>
                                    {{/each}}
                                </div>
                            {{/if}}
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- /Tabbed Card -->


    </div>
</div>


{{@include("footer", it)/}}


<script>
    //============================================== SSR Variables
    const permsDisableWhitelist = ('{{it.permsDisable.whitelist}}' === 'true');
    const permsDisableBan = ('{{it.permsDisable.ban}}' === 'true');



    //============================================== Action revocation
    //TODO: make an confirmation modal
    function revokeAction(action_id){
        if(!action_id){
            var notify = $.notify({ message: 'Invalid actionID' }, { type: 'danger' });
            return;
        }

        var notify = $.notify({ message: '<p class="text-center">Revoking...</p>' }, {});
        $.ajax({
            type: "POST",
            url: '/player/revoke_action',
            timeout: timeoutLong,
            data: {action_id},
            dataType: 'json',
            success: function (data) {
                if(data.refresh === true){
                    window.location.reload(true);
                }else{
                    notify.update('progress', 0);
                    notify.update('type', data.type);
                    notify.update('message', data.message);
                }
            },
            error: function (xmlhttprequest, textstatus, message) {
                notify.update('progress', 0);
                notify.update('type', 'danger');
                notify.update('message', message);
            }
        });
    }


    //============================================== Whitelist an ID via prompt or button click
    function whitelistID(reference){
        if(!reference){
            reference = prompt('Type in the whitelist Request ID (R####) or License Identifier.');
            if(!reference) return;
            reference = reference.trim();
        }
        console.dir(reference)
        
        //Treat input to improve UX
        if(reference.length == 5){
            reference = reference.toUpperCase();
        }else if(reference.length == 40){
            reference = reference.toLowerCase();
        }else if(reference.length == 48){
            reference = reference.substring(8).toLowerCase();
        }
        
        //Check input validity
        if(
            !/R[123456789ABCDEFGHJKLMNPQRSTUVWXYZ]{4}/.test(reference) && 
            !/[0-9A-Fa-f]{40}/.test(reference)
        ){
            var notify = $.notify({ message: 'The value inserted is not a valid Whitelist ID nor a license identifier.' }, { type: 'danger' });
            return;
        }

        var notify = $.notify({ message: '<p class="text-center">Whitelisting...</p>' }, {});
        $.ajax({
            type: "POST",
            url: '/player/whitelist',
            timeout: timeoutLong,
            data: {reference},
            dataType: 'json',
            success: function (data) {
                if(data.refresh === true){
                    window.location.reload(true);
                }else{
                    notify.update('progress', 0);
                    notify.update('type', data.type);
                    notify.update('message', data.message);
                }
            },
            error: function (xmlhttprequest, textstatus, message) {
                notify.update('progress', 0);
                notify.update('type', 'danger');
                notify.update('message', message);
            }
        });
    }



    //============================================== Search functionality
    const getSVG = (icon) => {
        return `<svg class="c-icon">
            <use xlink:href="img/coreui_icons.svg#cil-${icon}"></use>
        </svg>`;
    }
    const searchInput = document.getElementById('dbSearch-input');
    const searchButton = document.getElementById('dbSearch-button');
    const searchMessage = document.getElementById('dbSearch-message');
    const dbPlayersTab = document.getElementById('dbPlayers-tab');
    const dbPlayersContent = document.getElementById('dbPlayers-content');
    const dbPlayersSearchTab = document.getElementById('dbPlayers-tabSearch');
    const dbPlayersDefaultTab = document.getElementById('dbPlayers-tabDefault');
    const dbActionsTab = document.getElementById('dbActions-tab');
    const dbActionsContent = document.getElementById('dbActions-content');
    const dbActionsSearchTab = document.getElementById('dbActions-tabSearch');
    const dbActionsDefaultTab = document.getElementById('dbActions-tabDefault');

    //FIXME: if I change the text it should reset the button to "search" instead of "clear"
    searchButton.addEventListener('click', (e) => {
        if(searchButton.textContent.includes('Search')){
            performSearch();
        }else{
            clearSearch();
        }
    })
    searchInput.addEventListener('keyup', (e) => {
        if(e.keyCode !== 13) return;
        if(searchInput.value.length){
            performSearch();
        }else{
            clearSearch();
        }
    })

    //Clear search
    function clearSearch(){
        dbPlayersSearchTab.classList.add('d-none');
        dbPlayersDefaultTab.classList.remove('d-none');
        dbActionsSearchTab.classList.add('d-none');
        dbActionsDefaultTab.classList.remove('d-none');
        searchButton.innerHTML = getSVG('magnifying-glass') + ` Search`;
        searchInput.value = '';
        searchMessage.innerText = '';
        location.hash = '';
    }

    //Perform search
    function performSearch(){
        const searchString = searchInput.value.trim();
        location.hash = encodeURI(searchString);
        if(!searchString.length) return clearSearch();
        dbPlayersSearchTab.innerHTML = spinnerHTML;
        dbActionsSearchTab.innerHTML = spinnerHTML;
        dbPlayersSearchTab.classList.remove('d-none');
        dbPlayersDefaultTab.classList.add('d-none');
        dbActionsSearchTab.classList.remove('d-none');
        dbActionsDefaultTab.classList.add('d-none');
        searchButton.innerHTML = getSVG('x') + ` Clear`;
        searchMessage.innerText = '';

        $.ajax({
            type: "GET",
            url: '/player/list?search=' + encodeURI(searchString),
            timeout: timeoutLong,
            dataType: 'json',
            success: function (data) {
                if(data.error){
                    dbPlayersSearchTab.innerText = error;
                    dbActionsSearchTab.innerText = error;
                    return;
                }
                searchMessage.innerText = data.message;
                dbPlayersSearchTab.innerHTML = dbPlayersToHtml(data.resPlayers);
                dbActionsSearchTab.innerHTML = dbActionsToHtml(data.resActions);
                if(data.resPlayers.length && !data.resActions.length){
                    dbActionsTab.classList.remove('active');
                    dbActionsContent.classList.remove('show', 'active');
                    dbPlayersTab.classList.add('active');
                    dbPlayersContent.classList.add('show', 'active');
                }else if(data.resActions.length && !data.resPlayers.length){
                    dbPlayersTab.classList.remove('active');
                    dbPlayersContent.classList.remove('show', 'active');
                    dbActionsTab.classList.add('active');
                    dbActionsContent.classList.add('show', 'active');
                }
            },
            error: function (xmlhttprequest, textstatus, message) {
                dbPlayersSearchTab.innerText = message;
                dbActionsSearchTab.innerText = message;
            }
        });
    }

    //Converts players array to html
    function dbPlayersToHtml(players){
        if(!players.length){
            return `<div class="text-center">
                <h3 class="mx-auto pt-3 text-secondary">no players found</h3>
            </div>`;
        }else{
            const processed = players.map(p => `
                <div class="list-group-item list-group-item-accent-${xss(p.color)} logEntry logEntryClickable">
                    <div class="d-flex w-100 justify-content-between" onclick="showPlayer('${xss(p.license)}')"> 
                        <strong>${xss(p.name)}</strong>
                        <small>${xss(p.joined)}</small>
                    </div>
                </div>`);
            
            return [
                `<div class="list-group list-group-accent">`,
                ...processed,
                `</div>`
            ].join('\n');
        }
    }

    //Converts actions array to html
    function dbActionsToHtml(actions){
        if(!actions.length){
            return `<div class="text-center">
                <h3 class="mx-auto pt-3 text-secondary">no actions found</h3>
            </div>`;
        }else{
            const processed = actions.map(a => {
                let revokeButton = '';
                if(!permsDisableBan || !permsDisableWhitelist){
                    if(
                        a.isRevoked ||
                        a.type == 'warn' ||
                        (a.type == 'ban' && permsDisableBan) ||
                        (a.type == 'whitelist' && permsDisableWhitelist)
                    ){
                        revokeButton = `&nbsp;<span class="badge badge-outline-light txInlineBtn txActionsBtn">REVOKE</span>`; 
                    }else{
                        revokeButton = `&nbsp;<button onclick="revokeAction('${xss(a.id)}')" 
                                class="btn btn-secondary txInlineBtn txActionsBtn">REVOKE</button>`; 
                    }
                }
                const reason = (a.reason !== null)? xss(a.reason) : '';
                const footerNote = (a.footerNote)? `<small class="d-block">${xss(a.footerNote)}</small>` : '';
                return `<div class="list-group-item list-group-item-accent-${xss(a.color)} logEntry">
                    <div class="d-flex w-100 justify-content-between">
                        <strong>${a.message}</strong>
                        <small class="text-right">
                            <span class="text-monospace font-weight-bold">(${xss(a.id)})</span>
                            ${xss(a.date)}
                            ${revokeButton}
                        </small>
                    </div>
                    <span>${reason}</span>
                    ${footerNote}
                </div>`;
            });
            
            return [
                `<div class="list-group list-group-accent">`,
                ...processed,
                `</div>`
            ].join('\n');
        }
    }

    //Performs auto-search
    const urlHash = decodeURI(location.hash.substr(1).trim());
    if(urlHash.length){
        searchInput.value = urlHash;
        performSearch();
    }

    

    //============================================== Ban card
    const banCard = {
        identifiers: document.getElementById("frmAddBan-identifiers"),
        reason: document.getElementById("frmAddBan-reason"),
        durationSelect: document.getElementById("frmAddBan-durationSelect"),
        durationMultiplier: document.getElementById("frmAddBan-durationMultiplier"),
        durationUnit: document.getElementById("frmAddBan-durationUnit"),
        button: document.getElementById('frmAddBan-button'),
    }

    banCard.durationSelect.onchange = () => {
        const isDefault = (banCard.durationSelect.value !== 'custom');
        banCard.durationMultiplier.disabled = isDefault;
        banCard.durationUnit.disabled = isDefault;
    }

    banCard.button.onclick = () => {
        const frmIdentifiers = banCard.identifiers.value.trim();
        const reason = banCard.reason.value.trim();
        const data = {
            reason,
            duration: banCard.durationSelect.value === 'custom' ?
                `${banCard.durationMultiplier.value} ${banCard.durationUnit.value}` :
                banCard.durationSelect.value
        };

        if (!frmIdentifiers.length || !data.reason.length) {
            const notify = $.notify({ message: 'The identifiers and reason fields are required.' }, { type: 'warning' });
            return;
        }
        if (data.reason.length < 8) {
            const notify = $.notify({ message: 'The reason must be at least 8 characters.' }, { type: 'warning' });
            return;
        }
        data.reference = frmIdentifiers.split(/[,;'"\s]+/).filter(x => x.length);
        const notify = $.notify({ message: '<p class="text-center">Banning...</p>' }, {});

        banCard.identifiers.value = '';
        banCard.reason.value = '';

        $.ajax({
            type: "POST",
            url: '/player/ban',
            timeout: timeoutLong,
            data,
            dataType: 'json',
            success: function (data) {
                if(data.refresh === true){
                    window.location.reload(true);
                }else{
                    notify.update('progress', 0);
                    notify.update('type', data.type);
                    notify.update('message', data.message);
                }
            },
            error: function (xmlhttprequest, textstatus, message) {
                notify.update('progress', 0);
                notify.update('type', 'danger');
                notify.update('message', message);
            }
        });
    }
    
</script>
