<!--
 ~ Copyright 2022 youngmonkeys.org
 ~ 
 ~ Licensed under the ezyplatform, Version 1.0.0 (the "License");
 ~ you may not use this file except in compliance with the License.
 ~ You may obtain a copy of the License at
 ~ 
 ~     https://youngmonkeys.org/licenses/ezyplatform-1.0.0.txt
 ~ 
 ~ Unless required by applicable law or agreed to in writing, software
 ~ distributed under the License is distributed on an "AS IS" BASIS,
 ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ~ See the License for the specific language governing permissions and
 ~ limitations under the License.
-->

<!DOCTYPE html>
<html
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:th="http://www.thymeleaf.org"
        xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
        layout:decorate="~{ezyadmin}">

<body>
<div layout:fragment="content" class="row">
    <div class="col-lg-12">
        <table id="moduleList" class="table bg-white vertical-align-middle">
            <thead>
            <tr>
                <th style="width: 10px">#</th>
                <th>[[#{icon}]]</th>
                <th th:if="${moduleType == ''}">[[#{type}]]</th>
                <th>[[#{name}]]</th>
                <th>[[#{description}]]</th>
                <th class="text-center white-space-nowrap">[[#{latest_version}]]</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="module, iterator : ${modules}">
                <td class="text-center">
                    [[${iterator.index + 1}]]
                </td>
                <td>
                    <a th:href="${'/' + module.typeName + 's/' + module.name}">
                        <div class="rounded-circle image-button wh-72px">
                            <img class="object-fit-cover d-none" width="72" height="72"
                                th:classappend="${'project-icon-' + module.name}">
                            <span class="rounded-circle avatar-tmp wh-72px"
                                  th:classappend="${'project-icon-tmp-' + module.name}">
                                [[${#strings.capitalize(module.name.charAt(0))}]]
                            </span>
                        </div>
                    </a>
                </td>
                <td th:if="${moduleType == ''}">[[${module.type.displayName}]]</td>
                <td>
                    <div class="d-flex flex-column">
                        <p class="project-name" th:text="${module.projectName}"
                           th:attr="project-name-version=|${module.name + '-' + module.version + ':' + projectNewVersions.getOrDefault(module.name, module.version)}|"></p>
                        <button class="btn btn-link text-left p-0"
                                th:if="${module.name != 'socket-monitor' && module.active == true}" th:text="#{deactivate}"
                                th:attr="onclick=|ezyadmin.showDeactivateModuleModal('${module.typeName}', '${module.name}', '${module.projectName}', '${module.version}')|"></button>
                        <div th:if="${module.active == false}" class="d-flex">
                            <button class="btn btn-link text-left p-0" th:text="#{activate}"
                                    th:attr="onclick=|ezyadmin.showActivateModuleModal('${module.typeName}', '${module.name}', '${module.projectName}', '${module.version}')|"></button>
                            <span th:if="${module.name != 'welcome'}">|</span>
                            <button class="btn btn-link text-left p-0 text-danger" th:text="#{delete}"
                                    th:if="${module.name != 'welcome'}"
                                    th:attr="onclick=|ezyadmin.showDeleteModuleModal('${module.typeName}', '${module.name}', '${module.projectName}', '${module.version}')|"></button>
                        </div>
                    </div>
                </td>
                <td>
                    <div class="d-flex flex-column">
                        <div>
                            [[#{version}]]: <label th:text="${module.version}"></label>
                            |
                            [[#{by}]] <a th:href="${module.authorUrl}" th:text="${module.authorName}" target="_blank"
                                  th:classappend="${'author-of-' + module.name}"></a>
                        </div>
                        <div>
                            [[#{last_updated}]]: <label class="date-time-string" th:text="${module.lastUpdated}"></label>
                            |
                            <a th:href="${'/' + module.typeName + 's/' + module.name}" th:text="#{view_details}"></a>
                        </div>
                        <div th:if="${projectsContainsSqlScripts.contains(module.name)}">
                            [[#{sql_scripts}]]:
                            <a th:href="${'/api/v1/projects/' + module.name + '/sql'}" target="_blank">[[#{export}]]</a>
                        </div>
                    </div>
                </td>
                <td class="text-center">
                    <div class="d-flex flex-column">
                        <span th:id="${'update-to-date-' + module.name}">[[#{up_to_date}]]</span>
                        <button type="button" class="btn btn-link white-space-nowrap d-none"
                                th:id="${'update-from-market-' + module.name}"
                                th:attr="onclick=|ezyadmin.onUpdateButtonClick('${module.name}')|"></button>
                        <button type="button" class="btn btn-link white-space-nowrap"
                                onclick="ezyadmin.onUpdateManuallyButtonClick();">[[#{update_manually}]]</button>
                        <button type="button" class="btn btn-link white-space-nowrap"
                                th:attr="onclick=|ezyadmin.onRestartToApplyButtonClick(this, '${module.name}', '${module.projectName}', '${projectNewVersions.get(module.name)}')|"
                                th:if="${projectNewVersions.containsKey(module.name)}">
                            [[#{apply_version}]] [[${projectNewVersions.get(module.name)}]]
                            <i class="fas fa-info-circle text-info"
                               data-toggle="tooltip" data-placement="top"
                               th:title="#{restart_server_and_apply}"></i>
                        </button>
                    </div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</div>
<th:block layout:fragment="modals">
<th:block th:replace="~{modules/modals :: content}" />
<th:block th:replace="~{modules/modals :: upload-project}" />
<th:block th:replace="~{modules/modals :: update-to-latest-ezyplatform}" />
</th:block>
<script layout:fragment="scripts" th:inline="javascript">
/*<![CDATA[*/
ezyadmin.currentModuleType = /*[[${moduleType}]]*/ '';
ezyadmin.messages.update_to = /*[[#{update_to}]]*/ '';
/*]]>*/

ezyadmin.showLoadingScreen();

// ========== module list =============
ezyadmin.onNewButtonClick = function() {
    window.location = '/modules/add'
        + (ezyadmin.currentModuleType ? ('?type=' + ezyadmin.currentModuleType) : '')
        + (ezyadmin.lang ? ((ezyadmin.currentModuleType ? '&' : '?') + 'lang=' + ezyadmin.lang) : '');
}

ezyadmin.projectNames = [];
ezyadmin.projectVersions = {};
ezyadmin.projectNewVersions = {};
$(".project-name").each(function() {
    var projectNameVersion = $(this).attr('project-name-version');
    var lastIndex = projectNameVersion.lastIndexOf('-');
    var projectName = projectNameVersion.substring(0, lastIndex);
    if (!ezyadmin.projectNames.includes(projectName)) {
        ezyadmin.projectNames.push(projectName);
        var versions = projectNameVersion.substring(lastIndex + 1).split(':');
        ezyadmin.projectVersions[projectName] = versions[0];
        ezyadmin.projectNewVersions[projectName] = versions[1];
    }
});

ezyadmin.onUpdateButtonClick = function(projectName) {
    ezyadmin.installProject(
        projectName,
        ezyadmin.marketProjectVersions[projectName]
    );
}

ezyadmin.projectMapByName = {};
ezyadmin.getReleasedProjectsSimpleData = function() {
    if (!ezyadmin.projectNames.length) {
        ezyadmin.hideLoadingScreen();
        return;
    }
    $.ajax({
        url: '/api/v1/released-projects-simple-data?projectNames='
            + ezyadmin.projectNames.join(','),
        type: 'GET',
        dataType: 'json'
    })
    .done(function(data) {
        ezyadmin.marketProjectVersions = {};
        data.forEach(project => {
            ezyadmin.projectMapByName[project.name] = project;
            if (project.latestVersion) {
                ezyadmin.marketProjectVersions[project.name] = project.latestVersion.name
            }
        });
        ezyadmin.renderModulesInformation();
        ezyadmin.createDataTable('moduleList', 12);
        ezyadmin.hideLoadingScreen();
    })
    .fail(function(e) {
        ezyadmin.processGetApiErrors(e);
        ezyadmin.renderModulesInformation();
        ezyadmin.createDataTable('moduleList', 12);
        ezyadmin.hideLoadingScreen();
    });
}

ezyadmin.renderModulesInformation = function() {
    ezyadmin.projectNames.forEach(projectName => {
        var project = ezyadmin.projectMapByName[projectName];
        if (!project) {
            return;
        }
        $('.project-icon-tmp-' + project.name).addClass('d-none');
        $('.project-icon-' + project.name)
            .attr('src', '/api/v1/market/media/' + project.iconImageName)
            .removeClass('d-none');
        $('.author-of-' + project.name)
            .attr('href', ezyadmin.ezyplatformUrl + '/authors/' + project.author.uuid)
            .text(project.author.name);
        if (project.latestVersion
            && ezyadmin.compareVersions(project.latestVersion.name, ezyadmin.projectVersions[project.name])
            && ezyadmin.compareVersions(project.latestVersion.name, ezyadmin.projectNewVersions[project.name])
        ) {
            $('#update-to-date-' + project.name).addClass('d-none');
            $('#update-from-market-' + project.name)
                .text(ezyadmin.messages.update_to + ' ' + project.latestVersion.name)
                .removeClass('d-none');
        }
    });
}
ezyadmin.getReleasedProjectsSimpleData();
</script>
<th:block layout:fragment="post-scripts">
<script th:replace="~{modules/scripts :: scripts}" />
<script th:replace="~{modules/modals :: scripts}" />
<script th:replace="~{modules/modals :: upload-project-scripts}" />
<script th:replace="~{modules/modals :: update-to-latest-ezyplatform}" />
<script th:replace="~{ezyplatform/scripts :: scripts}" />
</th:block>
</body>
</html>
