<!--
 ~ 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">
    <div class="mb-4">
        <!-- Search form -->
        <div class="input-group md-form form-sm form-1 pl-0">
            <div class="input-group-prepend">
                    <span class="input-group-text purple lighten-3">
                        <i class="fas fa-search text-white" aria-hidden="true"></i>
                    </span>
            </div>
            <input class="form-control my-0 py-1" type="text" th:placeholder="#{search_modules}" aria-label="Search"
                   th:value="${searchModulesKeyword}" onkeydown="ezyadmin.onSearchModulesKeyDown(this);">
        </div>
    </div>
    <div class="row">
        <div class="col-12 row" id="moduleListBody">
        </div>
        <div class="col-12">
            <span><span id="projectCountText">0</span>
                [[${#strings.toLowerCase(#messages.msg('of'))}]]
                <span id="totalReleasedProjectText">0</span>
                [[${#strings.toLowerCase(#messages.msg('modules'))}]]
            </span>
            <ul class="pagination pagination-sm m-0 float-right">
                <li class="page-item">
                    <a class="page-link cursor-pointer" id="firstPageButton">
                        <i class="fas fa-arrow-circle-left pl-1 pr-1"></i>
                    </a>
                </li>
                <li class="page-item">
                    <a class="page-link cursor-pointer" id="prevPageButton">[[#{prev}]]</a>
                </li>
                <li class="page-item">
                    <a class="page-link cursor-pointer" id="nextPageButton">[[#{next}]]</a>
                </li>
                <li class="page-item">
                    <a class="page-link cursor-pointer" id="lastPageButton">
                        <i class="fas fa-arrow-circle-right pl-1 pr-1"></i>
                    </a>
                </li>
            </ul>
        </div>
    </div>
    <div class="mb-4"></div>
</div>
<th:block layout:fragment="modals">
<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.openBy = /*[[${openBy}]]*/ '';
ezyadmin.currentModuleType = /*[[${moduleType}]]*/ '';
ezyadmin.selectedModuleName = /*[[${selectedModuleName}]]*/ '';
ezyadmin.searchModulesKeyword = /*[[${searchModulesKeyword}]]*/ '';
ezyadmin.messages.add = /*[[#{add}]]*/;
ezyadmin.messages.buy = /*[[#{buy}]]*/;
ezyadmin.messages.category = /*[[#{category}]]*/;
ezyadmin.messages.created_by = /*[[#{created_by}]]*/;
ezyadmin.messages.tagline = /*[[#{tagline}]]*/;
ezyadmin.messages.version = /*[[#{version}]]*/;
ezyadmin.messages.last_updated = /*[[#{last_updated}]]*/;
ezyadmin.messages.view_details = /*[[#{view_details}]]*/;
/*]]>*/

// ========== upload module ==========
ezyadmin.onUploadButtonClick = function() {
    ezyadmin.showUploadProjectModal();
}

// ========== search modules =========
ezyadmin.onSearchModulesKeyDown = function(element) {
    if(event.key != 'Enter') {
        return;
    }
    var keyword = $(element).val();
    window.location = '/modules/add?' + (
        ezyadmin.currentModuleType
            ? 'type=' + ezyadmin.currentModuleType + '&keyword=' + keyword
            : 'keyword=' + keyword
    );
}

// ========== projects status =============
ezyadmin.fetchProjectVersionStatusList = function() {
    $.ajax({
        url: '/api/v1/projects/version-status',
        type: 'GET',
        dataType: 'json'
    })
    .done(function(projectVersionStatusList) {
        ezyadmin.existingProjectMap = {};
        projectVersionStatusList.forEach(e => {
            ezyadmin.existingProjectMap[e.projectName] = e;
        });
        ezyadmin.fetchReleasedProjectList();
    })
    .fail(function(e) {
    	ezyadmin.processGetApiErrors(e);
    });
}

// ========== user pagination =============
$('#firstPageButton').click(() => {
    ezyadmin.fetchReleasedProjectList('first');
});
$('#lastPageButton').click(() => {
    ezyadmin.fetchReleasedProjectList('last');
});
$('#nextPageButton').click(() => {
    ezyadmin.fetchReleasedProjectList('next');
});
$('#prevPageButton').click(() => {
    ezyadmin.fetchReleasedProjectList('prev');
});

// ========== project list =============
ezyadmin.fetchReleasedProjectList = function(action) {
    var queryString = '';
    if (ezyadmin.searchModulesKeyword) {
        queryString += '&keyword=' + ezyadmin.searchModulesKeyword;
    }
    if (action == 'next') {
        if (ezyadmin.lastReleasedProjectPageToken.next) {
            queryString += '&nextPageToken=' + ezyadmin.lastReleasedProjectPageToken.next;
        } else {
            return;
        }
    } else if (action == 'prev') {
        if (ezyadmin.lastReleasedProjectPageToken.prev) {
            queryString += '&prevPageToken=' + ezyadmin.lastReleasedProjectPageToken.prev;
        } else {
            return;
        }
    } else if (action == 'last') {
        queryString += '&lastPage=true';
    }
    var url = '/api/v1/released-projects?';
    if (ezyadmin.currentModuleType) {
        url += 'moduleType=' + ezyadmin.currentModuleType + '&';
    }
    if (ezyadmin.selectedModuleName) {
        url += 'projectName=' + ezyadmin.selectedModuleName + '&';
    }
    $.ajax({
        url: url + 'limit=12' + queryString,
        type: 'GET',
        dataType: 'json'
    })
    .done(function(data) {
        if (ezyadmin.openBy == 'marketSsoCallback'
            && ezyadmin.selectedModuleName
            && data.items.length == 1
            && data.items[0].name == ezyadmin.selectedModuleName
            && data.items[0].price > 0
            && data.items[0].buyStatus != 'PAID'
        ) {
            ezyadmin.openBy = '';
            window.location = ezyadmin.ezyplatformUrl +
                '/market/items/' +
                ezyadmin.selectedModuleName;
        }
        $('#projectCountText').text(data.count);
        $('#totalReleasedProjectText').text(ezyadmin.formatTotalResults(data.total));
        ezyadmin.lastReleasedProjectPageToken = data.pageToken;
        $('#moduleListBody').html(ezyadmin.buildReleasedProjectListBodyHtml(data.items));
        if (data.continuation.hasNext) {
            $('#nextPageButton').removeClass('text-secondary');
        } else {
            $('#nextPageButton').addClass('text-secondary');
        }
        if (data.continuation.hasPrevious) {
            $('#prevPageButton').removeClass('text-secondary');
        } else {
            $('#prevPageButton').addClass('text-secondary');
        }
    })
    .fail(function(e) {
    	ezyadmin.processGetApiErrors(e);
    });
}

ezyadmin.buildReleasedProjectListBodyHtml = function(projects) {
    var html = '';
    projects.forEach((project) => {
        html += ezyadmin.buildReleasedProjectListItemHtml(project);
    });
    return html;
}

ezyadmin.buildReleasedProjectListItemHtml = function(project) {
    var html = `
        <div class="col-lg-6 col-md-6 mb-3">
            <div class="d-flex flex-column bg-white border">
                <div class="d-flex p-3">
                    <div class="d-flex flex-column justify-content-between pr-3">
                        <img src="/api/v1/market/media/${project.iconImageName}" class="object-fit-cover" height="96px">
                        ${ezyadmin.existingProjectMap[project.name] ? `
                            <a class="btn btn-outline-primary mt-3 pt-1 pb-1" href="/${ezyadmin.currentModuleType || 'module'}s/${project.name}">
                                ${ezyadmin.messages.settings}
                            </a>
                        ` : project.latestVersion ? `
                            ${project.price && project.buyStatus !== 'PAID' ? `
                                <button type="button" class="btn btn-outline-primary mt-3 pt-1 pb-1" onclick="ezyadmin.openBuyProjectLink('${project.name}')">
                                    ${ezyadmin.messages.buy}
                                </button>
                            ` : `
                                <button class="btn btn-outline-primary mt-3 pt-1 pb-1" onclick="ezyadmin.installProject('${project.name}', '${project.latestVersion.name}')">
                                    ${ezyadmin.messages.add}
                                </button>
                            `}
                        ` : ''}
                    </div>
                    <div class="d-flex flex-column justify-content-between">
                        <h3>${project.displayName}</h3>
                        <span><strong>${ezyadmin.messages.category}</strong>: ${project.category ? project.category.displayName : ''}</span>
                        <span class="pt-2"><strong>${ezyadmin.messages.tagline}</strong>: ${project.shortDescription}</span>
                        <span class="pt-2"><strong>${ezyadmin.messages.description}</strong>: ${ezyadmin.removeHtmlTagAndSub(project.description, 180)}</span>
                        <div class="d-flex pt-3">
                            <span class="pr-3">${ezyadmin.messages.created_by}
                                <a href="${ezyadmin.ezyplatformUrl}/authors/${project.author.uuid}" target="_blank">
                                    ${project.author.name}
                                </a>
                            </span>
                            <a href="${ezyadmin.ezyplatformUrl}/market/items/${project.name}" target="_blank">
                                ${ezyadmin.messages.view_details}
                            </a>
                        </div>
                    </div>
                </div>
                <div class="d-flex justify-content-between bg-light border-top p-3">
                    <span><label class="m-0">${ezyadmin.messages.version}</label>: ${project.latestVersion ? project.latestVersion.name : 'unknown'}</span>
                    <span><label class="m-0">${ezyadmin.messages.last_updated}</label>:
                        ${project.latestVersion ? ezyadmin.getTimeRangeTextValue(project.latestVersion.updatedAt) : 'unknown'}
                    </span>
                </div>
            </div>
        </div>
        `;
    return html;
}

ezyadmin.fetchProjectVersionStatusList();
</script>
<th:block layout:fragment="post-scripts">
<script th:replace="~{modules/scripts :: scripts}" />
<script th:replace="~{modules/modals :: upload-project-scripts}" />
<script th:replace="~{modules/modals :: update-to-latest-ezyplatform}" />
</th:block>
</body>
</html>
