<%- await include('basic/header.html', locals) %>

<div class="text-center mb-4">
    <h2>Resources List</h2>
</div>


<div class="row justify-content-center">
    <div class="col-md-7 mw-col6">
        <div class="card card-accent-info">
            <div class="card-header float-left">
                <span style="font-size: large">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" type="text" name="resource" id="resourceInput" onkeyup="findResource()"
                    placeholder="Find resource by name..." style="margin-top: 1em;">
                <div class="row justify-content-center">
                    <span class="form-text text-muted" style="margin-top: calc(0.3rem + 2px)">
                        Default resources:
                    </span>
                    &nbsp;&nbsp;
                    <label class="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="On" data-unchecked="Off"></span>
                    </label>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="row justify-content-center">
    <div class="col-sm-12 col-lg-7 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('basic/footer.html', 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",
    ]


    //============================================== Refresh List
    $('#btnRefresh').click(function () {
        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 !== 'danger'){
                    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);
            }
        });
    })


    //============================================== Refresh button
    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 !== 'danger'){
                    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 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){
            setDefaultResourcesVisibility();
        }

    }

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

    function setDefaultResourcesVisibility() {
        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");
            })
        }

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

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

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