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


<div class="row justify-content-center">
    <div class="col-md-8 mw-col6">
        <div class="card card-accent-info">
            <div class="card-header float-left">
                <span class="h5">All Resources</span>
                <button class="btn btn-sm btn-primary float-right" type="button" id="btnRefresh" <%= disableActions %>>
                    <i class="icon-refresh"></i> Reload & Refresh
                </button>
                <input class="form-control mt-3" type="text" name="resource" id="resourceInput" onkeyup="findResource()"
                    placeholder="Find resource by name...">
                <div class="row justify-content-center pt-2">
                    <span class="form-text text-muted mr-1">
                        Default resources:
                    </span>
                    
                    <label class="switch-lg c-switch c-switch-label c-switch-pill c-switch-success fix-pill-form">
                        <input type="checkbox" id="defResCheckbox" class="c-switch-input">
                        <span class="c-switch-slider" data-checked="Show" data-unchecked="Hide"></span>
                    </label>
                    
                    <span class="form-text text-muted ml-3 mr-1">
                        Only stopped resources:
                    </span>
                    
                    <label class="switch-lg c-switch c-switch-label c-switch-pill c-switch-success fix-pill-form">
                        <input type="checkbox" id="stoppedResCheckbox" class="c-switch-input">
                        <span class="c-switch-slider" data-checked="Show" data-unchecked="Hide"></span>
                    </label>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="row justify-content-center">
    <div class="col-sm-12 col-lg-8 mw-col8">
        <div class="card card-accent-info table-responsive-sm">
            <table class="table table-hover table-outline mb-0">
                <% for (const resGroup of resGroups) { %>
                    <thead class="thead-light" id="resList-card-<%= resGroup.divName %>">
                        <tr>
                            <th class="text-break text-center" colspan="2"><%= resGroup.subPath %></th>
                        </tr>
                    </thead>
                    <tbody id="resList-cardBody-<%= resGroup.divName %>"
                        aria-labelledby="resList-cardHeader-<%= resGroup.divName %>">
                        <% for (const resource of resGroup.resources) { %>
                            <tr id="res-<%= resource.divName %>">
                                <td>
                                    <strong style="word-wrap: break-word;"><%= resource.name %></strong>
                                    <% if (resource.version !== '') { %>
                                        <em><%= resource.version %></em>
                                    <% } %>
                                    <% if (resource.author !== '') { %>
                                        by <%= resource.author %>
                                    <% } %>
                                    <% if (resource.description !== '') { %>
                                        <br/>
                                        <%= resource.description %>
                                    <% } %>
                                </td>

                                <td class="tableActions">
                                    <% if (resource.status === 'started') { %>
                                    <a class="btn btn-sm btn-outline-warning d-block d-md-inline-block mr-md-1 mb-1 mb-md-0 <%= disableActions %>"
                                        href="#"
                                        onclick="btnCommand('ensure_res', '<%= resource.name %>'); event.preventDefault();" <%= disableActions %>>
                                        Restart
                                    </a>
                                    <a class="btn btn-sm btn-outline-danger d-block d-md-inline-block m-0 <%= disableActions %>"
                                        href="#"
                                        onclick="btnCommand('stop_res', '<%= resource.name %>'); event.preventDefault();" <%= disableActions %>>
                                        Stop
                                    </a>
                                    <% } else { %>
                                    <a class="btn btn-sm btn-outline-success d-block d-md-inline-block <%= disableActions %>"
                                        href="#"
                                        onclick="btnCommand('ensure_res', '<%= resource.name %>'); event.preventDefault();" <%= disableActions %>>
                                        Start
                                    </a>
                                    <% } %>
                                </td>
                            </tr>
                        <% } %> 
                        <%# End individual resource loop %>
                    </tbody>
                <% } %>
                <%# End resource group loop %>
            </table>
        </div>
    </div>
</div>


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




<script>
    //NOTE: this is hacky af, but whatever
    const resGroupsJS = JSON.parse(atob(`<%= (Buffer.from(resGroupsJS).toString('base64')) %>`));
    
    const defaultResources = [
        "baseevents",
        "basic-gamemode",
        "betaguns", //old
        "channelfeed", //old
        "chat-theme-gtao",
        "chat",
        "example-loadscreen",
        "fivem-awesome1501", //old
        "fivem-map-hipster",
        "fivem-map-skater",
        "fivem",
        "gameInit", //old
        "hardcap",
        "irc", //old
        "keks", //old
        "mapmanager",
        "money-fountain-example-map",
        "money-fountain",
        "money",
        "monitor",
        "obituary-deaths", //old
        "obituary", //old
        "ped-money-drops",
        "player-data",
        "playernames",
        "race-test", //old
        "race", //old
        "rconlog",
        "redm-map-one",
        "runcode",
        "scoreboard",
        "sessionmanager-rdr3",
        "sessionmanager",
        "spawnmanager",
        "webadmin",
        "webpack",
        "yarn",
    ]

    const convErrorType = (x) => x === 'error' ? 'danger' : x;


    //============================================== Refresh List
    $('#btnRefresh').click(() => {
        const notify = $.notify({ message: '<p class="text-center">Executing Command...</p>' }, {});
        txAdminAPI({
            type: "POST",
            url: '/fxserver/commands',
            timeout: REQ_TIMEOUT_LONG,
            data: { action: 'refresh_res', parameter: '' },
            success: function (data) {
                if(data.type !== 'error'){
                    window.location.reload(true);
                }else{
                    notify.update('progress', 0);
                    notify.update('type', convErrorType(data.type));
                    notify.update('message', data.msg);
                }
            },
            error: function (xmlhttprequest, textstatus, message) {
                notify.update('progress', 0);
                notify.update('type', 'danger');
                notify.update('message', message);
            }
        });
    })


    //============================================== Start/Stop/Restart buttons
    function btnCommand(action, parameter) {
        const notify = $.notify({ message: '<p class="text-center">Executing Command...</p>' }, {});
        txAdminAPI({
            type: "POST",
            url: '/fxserver/commands',
            data: { action, parameter },
            success: function (data) {
                if(data.type !== 'error'){
                    window.location.reload(true);
                }else{
                    notify.update('progress', 0);
                    notify.update('type', convErrorType(data.type));
                    notify.update('message', data.msg);
                }
            },
            error: function (xmlhttprequest, textstatus, message) {
                notify.update('progress', 0);
                notify.update('type', 'danger');
                notify.update('message', message);
            }
        });
    }

    //============================================== Search function
    function findResource() {
        const inputEl = document.getElementById("resourceInput");
        const filter = inputEl.value.toUpperCase();

        resGroupsJS.forEach(folder => {
            let hidden = 0;
            folder.resources.forEach(resource => {
                if (resource.name.toUpperCase().indexOf(filter) > -1) {
                    $(`#res-${resource.divName}`).show();
                } else {
                    hidden++;
                    $(`#res-${resource.divName}`).hide();
                }
            });
            if (folder.resources.length == hidden) {
                $(`#resList-card-${folder.divName}`).hide();
            } else {
                $(`#resList-card-${folder.divName}`).show();
            }
        });
        if(!filter.length){
            refreshResourceList();
        }
    }

    //============================================== Hide defaults
    $('#defResCheckbox').click(() => {
        window.localStorage.resourcesPageShowDefault = document.getElementById('defResCheckbox').checked;
        refreshResourceList();
    });

    $('#stoppedResCheckbox').click(() => {
        window.localStorage.resourcesPageShowStopped = document.getElementById('stoppedResCheckbox').checked;
        refreshResourceList();
    })

    function refreshResourceList() {
        if ($('#defResCheckbox').is(':checked')) {
            defaultResources.forEach(defRes => {
                $(`#res-${defRes}`).show();
                $(`#res-${defRes}`).removeClass("defaultRes");
            })
        } else {
            defaultResources.forEach(defRes => {
                $(`#res-${defRes}`).hide();
                $(`#res-${defRes}`).addClass("defaultRes");
            })
        }

        const onlyStopped = $('#stoppedResCheckbox').is(':checked')
        resGroupsJS.forEach(folder => {
            let hidden = 0;

            folder.resources.forEach(resource => {
                if ($(`#res-${resource.divName}`).hasClass("defaultRes")) {
                    hidden++;
                    return
                }

                if (onlyStopped && resource.status !== 'stopped') {
                    $(`#res-${resource.divName}`).hide()
                    hidden++;
                } else {
                    $(`#res-${resource.divName}`).show()
                }
            });

            if (folder.resources.length === hidden) {
                $(`#resList-card-${folder.divName}`).hide();
            } else {
                $(`#resList-card-${folder.divName}`).show();
            }
        });
    }

    $(() => {
        if (typeof window.localStorage.resourcesPageShowDefault === 'string') {
            document.getElementById('defResCheckbox').checked = (window.localStorage.resourcesPageShowDefault === 'true');
        } else {
            window.localStorage.resourcesPageShowDefault = false;
        }

        document.getElementById('stoppedResCheckbox').checked = window.localStorage.resourcesPageShowStopped === 'true'

        refreshResourceList();
    });
</script>
