<!--
 ~ 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 type="search" class="form-control my-0 py-1" 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.rating = /*[[#{rating}]]*/;
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.currentMarketIndex = 0;
ezyadmin.currentMarketUrl = ezyadmin.marketUrls[0];

ezyadmin.lastMarketIndex = function() {
    return ezyadmin.marketUrls.length - 1;
}

ezyadmin.fetchReleasedProjectList = function(action) {
    var pageToken = ezyadmin.lastReleasedProjectPageToken || {};
    var queryString = '';
    if (action == 'next') {
        if (pageToken.next) {
            queryString += '&nextPageToken=' + pageToken.next;
        } else if (ezyadmin.currentMarketIndex < ezyadmin.lastMarketIndex()) {
            ezyadmin.currentMarketIndex += 1;
        } else {
            return;
        }
    } else if (action == 'prev') {
        if (pageToken.prev) {
            queryString += '&prevPageToken=' + pageToken.prev;
        } else if (ezyadmin.currentMarketIndex > 0) {
            ezyadmin.currentMarketIndex -= 1;
            queryString += '&lastPage=true';
        } else {
            return;
        }
    } else if (action == 'last') {
        ezyadmin.currentMarketIndex = ezyadmin.lastMarketIndex();
        queryString += '&lastPage=true';
    } else {
        ezyadmin.currentMarketIndex = 0;
    }
    ezyadmin.doFetchReleasedProjectList(
        queryString,
        action == 'prev' || action == 'last' ? 'backward' : 'forward'
    );
}

ezyadmin.fetchReleasedProjectListOfOtherMarket = function(direction) {
    if (direction == 'forward'
        && ezyadmin.currentMarketIndex < ezyadmin.lastMarketIndex()
    ) {
        ezyadmin.currentMarketIndex += 1;
        ezyadmin.doFetchReleasedProjectList('', direction);
        return true;
    }
    if (direction == 'backward' && ezyadmin.currentMarketIndex > 0) {
        ezyadmin.currentMarketIndex -= 1;
        ezyadmin.doFetchReleasedProjectList('&lastPage=true', direction);
        return true;
    }
    return false;
}

ezyadmin.doFetchReleasedProjectList = function(queryString, direction) {
    ezyadmin.currentMarketUrl = ezyadmin.marketUrls[ezyadmin.currentMarketIndex];
    var url = '/api/v1/released-projects?marketUrl='
        + encodeURIComponent(ezyadmin.currentMarketUrl) + '&';
    if (ezyadmin.searchModulesKeyword) {
        url += 'keyword=' + ezyadmin.searchModulesKeyword + '&';
    }
    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 (!data.items.length
            && ezyadmin.fetchReleasedProjectListOfOtherMarket(direction)
        ) {
            return;
        }
        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.currentMarketUrl +
                '/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
            || ezyadmin.currentMarketIndex < ezyadmin.lastMarketIndex()
        ) {
            $('#nextPageButton').removeClass('text-secondary');
        } else {
            $('#nextPageButton').addClass('text-secondary');
        }
        if (data.continuation.hasPrevious || ezyadmin.currentMarketIndex > 0) {
            $('#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 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="${ezyadmin.buildMarketMediaUrl(project.iconImageName, ezyadmin.currentMarketUrl)}" 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.currentMarketUrl}')">
                                    ${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 d-flex align-items-center"><strong>${ezyadmin.messages.rating}</strong>:&nbsp;${ezyadmin.buildStarsHtml(project.ratingScore, project.ratingCount, ezyadmin.currentMarketUrl + '/market/items/' + project.name)}</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.currentMarketUrl}/authors/${project.author.uuid}" target="_blank">
                                    ${project.author.name}
                                </a>
                            </span>
                            <a href="${ezyadmin.currentMarketUrl}/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">
    <th:block th:replace="~{modules/scripts :: scripts}" />
    <th:block th:replace="~{modules/modals :: upload-project-scripts}" />
    <th:block th:replace="~{modules/modals :: update-to-latest-ezyplatform}" />
    <th:block th:replace="~{fragments/stars :: scripts}" />
</th:block>
</body>
</html>
