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

<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" {{it.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">
                {{@each(it.resGroups) => resGroup}}
                    <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}}">
                        {{@each(resGroup.resources) => resource}}
                            <tr id="res-{{resource.divName}}">
                                <td>
                                    <strong style="word-wrap: break-word;">{{resource.name}}</strong>
                                    {{@if(resource.version!='')}}
                                        <em>{{resource.version}}</em>
                                    {{/if}}
                                    {{@if(resource.author!='')}}
                                        by {{resource.author}}
                                    {{/if}}
                                    {{@if(resource.description!='')}}
                                        <br>
                                        {{resource.description}}
                                    {{/if}}
                                </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 {{it.disableActions}}"
                                        href="#"
                                        onclick="btnCommand('ensure_res', '{{resource.name}}'); event.preventDefault();" {{it.disableActions}}>
                                        Restart
                                    </a>
                                    <a class="btn btn-sm btn-outline-danger d-block d-md-inline-block m-0 {{it.disableActions}}"
                                        href="#"
                                        onclick="btnCommand('stop_res', '{{resource.name}}'); event.preventDefault();" {{it.disableActions}}>
                                        Stop
                                    </a>
                                    {{#else}}
                                    <a class="btn btn-sm btn-outline-success d-block d-md-inline-block {{it.disableActions}}"
                                        href="#"
                                        onclick="btnCommand('ensure_res', '{{resource.name}}'); event.preventDefault();" {{it.disableActions}}>
                                        Start
                                    </a>
                                    {{/if}}
                                </td>
                            </tr>
                        {{/each}}
                    </tbody>
                {{/each}}
            </table>
        </div>
    </div>
</div>


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




<script>
    //NOTE: this is hacky af, but whatever
    const resGroupsJS = JSON.parse(atob(`{{it.resGroupsJS|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>
