<!--
 ~ 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-12">
        <div class="row">
            <div class="col-lg-3"></div>
            <div class="col-lg-3 col-md-4 page-search">
                <label for="adminSearchStatus" class="white-space-nowrap">
                    [[#{status}]]:
                </label>
                <select class="form-control form-select" id="adminSearchStatus"
                        onchange="ezyadmin.onAdminStatusSelected();">
                    <option value="">[[#{all}]]</option>
                    <option th:each="adminStatus : ${adminStatuses}"
                            th:value="${adminStatus}"
                            th:selected="${adminStatus == adminSearchStatus}">
                        [[#{${adminStatus.toLowerCase()}}]]
                    </option>
                </select>
            </div>
            <div class="col-lg-3 col-md-5 page-search">
                <label for="adminSearchKeyword" class="white-space-nowrap">
                    [[#{search}]]:
                </label>
                <input type="search" class="form-control" th:value="${adminSearchKeyword}"
                       th:placeholder="#{keyword}" id="adminSearchKeyword"
                       oninput="ezyadmin.onKeydownToSearchAdmin();"
                       onkeydown="ezyadmin.onKeydownToSearchAdmin();">
            </div>
            <div class="col-lg-3 col-md-4 page-search">
                <label for="adminSearchLimit" class="white-space-nowrap">
                    [[#{limit}]]:
                </label>
                <select class="form-control" id="adminSearchLimit"
                        onchange="ezyadmin.onAdminSearchLimitChanged();">
                    <option value="30" selected>30 [[#{item_s}]]</option>
                    <option value="50">50 [[#{item_s}]]</option>
                    <option value="100">100 [[#{item_s}]]</option>
                    <option value="200">200 [[#{item_s}]]</option>
                    <option value="300">300 [[#{item_s}]]</option>
                    <option value="500">500 [[#{item_s}]]</option>
                </select>
            </div>
        </div>
    </div>
    <div class="col-lg-12">
        <div class="card">
            <div class="card-body table-responsive p-0">
                <table id="adminListTable" class="table table-bordered table-hover text-nowrap align-middle-cells">
                    <thead>
                    <tr>
                        <th class="text-center pl-2p5">
                            <input type="checkbox" onclick="ezyadmin.onMultiAdminsClick(this)" class="wh-1rem" />
                        </th>
                        <th class="text-center">[[#{id}]]</th>
                        <th class="text-center">[[#{avatar}]]</th>
                        <th>[[#{username}]]</th>
                        <th>[[#{display_name}]]</th>
                        <th>[[#{email}]]</th>
                        <th class="text-center">[[#{phone}]]</th>
                        <th class="text-center">[[#{job_title}]]</th>
                        <th class="text-center">[[#{status}]]</th>
                        <th class="text-center">[[#{created_at}]]</th>
                        <th class="text-center">[[#{actions}]]</th>
                    </tr>
                    </thead>
                    <tbody id="adminListBody">
                    </tbody>
                </table>
            </div>
            <!-- /.card-body -->
            <div class="card-footer clearfix">
                <span>
                    <span id="adminCountText">0</span>
                    [[${#strings.toLowerCase(#messages.msg('of'))}]]
                    <span id="totalAdminText">0</span>
                    [[${#strings.toLowerCase(#messages.msg('admins'))}]]
                </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>
            <!-- /.card-footer -->
        </div>
    </div>
</div>
<script layout:fragment="scripts" th:inline="javascript">
/*<![CDATA[*/
ezyadmin.adminSearchKeyword = /*[[${adminSearchKeyword}]]*/;
ezyadmin.accessibleUris['/admins/{username}'] = /*[[${adminRoles.isAccessible('/admins/{username}')}]]*/;
ezyadmin.accessibleUris['/admins/{username}/edit'] = /*[[${adminRoles.isAccessible('/admins/{username}/edit')}]]*/;
ezyadmin.accessibleUris['/api/v1/admins/{username}/activate'] = /*[[${adminRoles.isAccessible('/api/v1/admins/{username}/activate', 'PUT')}]]*/;
ezyadmin.accessibleUris['/api/v1/admins/{username}/archive'] = /*[[${adminRoles.isAccessible('/api/v1/admins/{username}/archive', 'PUT')}]]*/;
ezyadmin.accessibleUris['/api/v1/admins/{username}/block'] = /*[[${adminRoles.isAccessible('/api/v1/admins/{username}/block', 'PUT')}]]*/;
ezyadmin.accessibleUris['/api/v1/admins/{username}/delete'] = /*[[${adminRoles.isAccessible('/api/v1/admins/{username}', 'DELETE')}]]*/;
/*]]>*/

ezyadmin.adminSearchLimit = 30;
ezyadmin.adminIdChecks = {};
ezyadmin.checkedAdminIds = [];
ezyadmin.adminById = {};

// ========== admin init =============
ezyadmin.onNewButtonClick = function() {
    window.location = '/admins/add'
        + (ezyadmin.lang ? '?lang=' + ezyadmin.lang : '');
}

// ========== admin search =============
ezyadmin.onKeydownToSearchAdmin = function() {
    var before = ezyadmin.adminSearchKeyword;
    ezyadmin.adminSearchKeyword = $('#adminSearchKeyword').val();
    if(event.key === 'Enter' || (before && !ezyadmin.adminSearchKeyword)) {
        ezyadmin.fetchAdminList();
        ezyadmin.changeBrowserUrl();
    }
}

ezyadmin.onAdminStatusSelected = function() {
    ezyadmin.adminSearchStatus = $('#adminSearchStatus').val();
    ezyadmin.fetchAdminList();
    ezyadmin.changeBrowserUrl();
}

ezyadmin.onAdminSearchLimitChanged = function() {
    ezyadmin.adminSearchLimit = $('#adminSearchLimit').val();
    ezyadmin.fetchAdminList();
    ezyadmin.changeBrowserUrl();
}

ezyadmin.changeBrowserUrl = function() {
    var params = [];
    if (ezyadmin.adminSearchKeyword) {
        params.push('keyword=' + ezyadmin.adminSearchKeyword);
    }
    if (ezyadmin.adminSearchStatus) {
        params.push('adminStatus=' + ezyadmin.adminSearchStatus);
    }
    if (ezyadmin.adminSearchLimit) {
        params.push('limit=' + ezyadmin.adminSearchLimit);
    }
    if (ezyadmin.lang) {
        params.push('lang=' + ezyadmin.lang);
    }
    var url = location.pathname;
    if (params.length) {
        url += '?' + params.join('&');
    }
    window.history.pushState({}, '', url);
}

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

// ========== admin list =============
ezyadmin.fetchAdminList = function(action) {
    var queryString = '';
    var limit = ezyadmin.adminSearchLimit || 12;
    if (ezyadmin.adminSearchKeyword) {
        queryString += '&keyword=' + ezyadmin.adminSearchKeyword;
    }
    if (ezyadmin.adminSearchStatus) {
        queryString += '&adminStatus=' + ezyadmin.adminSearchStatus;
    }
    if (action == 'current') {
        if (ezyadmin.lastAdminQueryString) {
            queryString = ezyadmin.lastAdminQueryString;
        }
    } else if (action == 'next') {
        if (ezyadmin.lastAdminPageToken.next) {
            queryString += '&nextPageToken=' + ezyadmin.lastAdminPageToken.next;
        } else {
            return;
        }
    } else if (action == 'prev') {
        if (ezyadmin.lastAdminPageToken.prev) {
            queryString += '&prevPageToken=' + ezyadmin.lastAdminPageToken.prev;
        } else {
            return;
        }
    } else if (action == 'last') {
        queryString += '&lastPage=true';
    }
    $.ajax({
        type: 'GET',
        url: '/api/v1/admins?limit=' + limit + queryString,
        contentType: 'application/json',
        success: function (data) {
            data.items.forEach((admin) => {
                ezyadmin.adminById[admin.id] = admin;
            });
            $('#adminCountText').text(data.count);
            $('#totalAdminText').text(ezyadmin.formatTotalResults(data.total));
            ezyadmin.lastAdminQueryString = queryString;
            ezyadmin.lastAdminPageToken = data.pageToken;
            $('#adminListBody').html(ezyadmin.buildAdminListBodyHtml(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');
            }
        },
        error: function (data) {
            ezyadmin.processGetApiErrors(data);
        }
    });
}

ezyadmin.buildAdminListBodyHtml = function(adminList) {
    var html = '';
    adminList.forEach((admin) => {
        html += ezyadmin.buildAdminListItemHtml(admin);
    });
    return html;
}

ezyadmin.buildAdminListItemHtml = function(admin) {
    var statusColor = ezyadmin.getTextColorByStatus(admin.status);
    var html = `
        <tr>
            <td class="px-3">
                <input name="adminIds"
                       type="checkbox"
                       value="${admin.id}"
                       onclick="ezyadmin.onAdminCheckChange(this)"
                       ${ezyadmin.adminIdChecks[admin.id] ? 'checked' : ''}
                       class="wh-1rem">
            </td>
            <td class="text-center">${admin.id}</td>
            <td class="text-center">
    `;
    if (admin.avatar) {
        html += `
            <img class="common-avatar-img" src="${ezyadmin.extractMediaUrl(admin.avatar)}">
        `;
    }
    html += `
            </td>
            <td>
                <a href="/admins/${admin.username}${ezyadmin.lang ? `?lang=${ezyadmin.lang}` : ''}">
                    ${admin.username}
                </a>
            </td>
            <td>${admin.displayName || ''}</td>
            <td><a href="mailto:${admin.email}">${admin.email}</a></td>
            <td class="text-center"><a href="tel:${admin.phone}">${admin.phone || ''}</a></td>
            <td class="text-center">${admin.jobTitle || ''}</td>
            <td class="text-center ${statusColor}">${ezyadmin.getI18nMessage(admin.status.toLowerCase())}</td>
            <td class="text-center">${ezyadmin.formatTimeStamp(admin.createdAt)}</td>
            <td class="text-center">
                ${admin.username === ezyadmin.adminUsername || ezyadmin.accessibleUris['/admins/{username}'] ? `
                    <a class="btn btn-link pr-1" href="/admins/${admin.username}${ezyadmin.lang ? `?lang=${ezyadmin.lang}` : ''}">
                        <i class="fas fa-eye text-info"></i>
                    </a>
                ` : ''}
                ${admin.username === ezyadmin.adminUsername || ezyadmin.accessibleUris['/admins/{username}/edit'] ? `
                    <button type="button" class="btn btn-link px-1" onclick="ezyadmin.editAdmin('${admin.username}')">
                        <i class="fas fa-edit text-primary"></i>
                    </button>
                ` : ''}
                ${admin.status === 'ACTIVATED' && ezyadmin.accessibleUris['/api/v1/admins/{username}/archive'] ? `
                    <button class="btn btn-link px-1" onclick="ezyadmin.archiveAdmin('${admin.username}')">
                        <i class="fas fa-archive text-danger"></i>
                    </button>
                ` : ''}
                ${admin.status === 'ACTIVATED' && ezyadmin.accessibleUris['/api/v1/admins/{username}/block'] ? `
                    <button class="btn btn-link pl-1" onclick="ezyadmin.blockAdmin('${admin.username}')">
                        <i class="fas fa-ban text-danger"></i>
                    </button>
                ` : ''}
                ${admin.status !== 'ACTIVATED' && ezyadmin.accessibleUris['/api/v1/admins/{username}/activate'] ? `
                    <button class="btn btn-link px-1" onclick="ezyadmin.activateAdmin('${admin.username}')">
                        <i class="fas fa-location-arrow text-success"></i>
                    </button>
                ` : ''}
                ${(admin.status == 'INACTIVATED' || admin.status == 'ARCHIVED' || admin.status == 'BLOCKED') && ezyadmin.accessibleUris['/api/v1/admins/{username}/block'] ? `
                    <button class="btn btn-link pl-1" onclick="ezyadmin.deleteAdmin('${admin.username}')">
                        <i class="fas fa-trash text-danger"></i>
                    </button>
                ` : ''}
            </td>
        </tr>
        `;
	return html;
}
ezyadmin.fetchAdminList();

// ============== admin actions =============
ezyadmin.editAdmin = function(username) {
    var url = username == ezyadmin.adminUsername
        ? '/admins/me/edit'
        : '/admins/' + username + '/edit';
    window.location = url + (ezyadmin.lang ? '?lang=' + ezyadmin.lang : '');
}

// =============== do admins actions ========
ezyadmin.onMultiAdminsClick = function(e) {
    var checked = $(e).prop('checked');
    ezyadmin.checkedAdminIds = [];
    $('input[name="adminIds"]').each(function() {
        var checkbox = $(this);
        var adminId = parseInt(checkbox.val());
        ezyadmin.adminIdChecks[adminId] = checked;
        checkbox.prop('checked', checked);
        if (checked) {
            ezyadmin.checkedAdminIds.push(adminId);
        }
    });
    ezyadmin.updateTaggableEntityFromCheckedAdminIds();
}

ezyadmin.onAdminCheckChange = function(checkbox) {
    var adminId = parseInt(checkbox.value);
    ezyadmin.adminIdChecks[adminId] = checkbox.checked;
    if (checkbox.checked) {
        if (ezyadmin.checkedAdminIds.indexOf(adminId) < 0) {
            ezyadmin.checkedAdminIds.push(adminId);
        }
    } else {
        ezyadmin.removeItemFromList(ezyadmin.checkedAdminIds, adminId);
    }
    ezyadmin.updateTaggableEntityFromCheckedAdminIds();
}

ezyadmin.updateTaggableEntityFromCheckedAdminIds = function() {
    if (!ezyadmin.checkedAdminIds.length) {
        ezyadmin.taggableEntity = null;
        return;
    }
    var lastCheckedAdminId = ezyadmin.checkedAdminIds[ezyadmin.checkedAdminIds.length - 1];
    var admin = ezyadmin.adminById[lastCheckedAdminId];
    if (!admin) {
        return;
    }
    ezyadmin.taggableEntity = {
        id: admin.id,
        code: admin.username,
        displayName: admin.displayName || admin.username,
        type: 'ezy_admins'
    };
}
</script>
<th:block layout:fragment="post-scripts">
    <th:block th:replace="~{admins/scripts :: update}" />
</th:block>
</body>
</html>
