<!--
 ~ 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 mb-2 selected-user-count d-none"></div>
    <div class="col-12">
        <div class="row">
            <div class="col-lg-3 col-md-4 page-search">
                <div class="d-flex align-items-center w-100">
                    <select class="form-control form-select" id="userBulkAction">
                        <option value="">[[#{bulk_action}]]</option>
                        <option value="IMPORT_USERS_FROM_FILE">[[#{import_users_from_file}]]</option>
                        <option value="ACTIVATE">[[#{activate_users}]]</option>
                        <option value="ACTIVATE">[[#{activate_users}]]</option>
                        <option value="ARCHIVE">[[#{archive_users}]]</option>
                        <option value="ERASE">[[#{erase_users}]]</option>
                        <option value="DELETE">[[#{delete_users}]]</option>
                    </select>
                    <button type="button" class="btn btn-outline-primary text-nowrap ml-1"
                            onclick="ezyadmin.performUserBulkAction();">
                        [[#{perform}]]
                    </button>
                </div>
            </div>
            <div class="col-lg-3 col-md-4 page-search">
                <label for="userSearchStatus" class="white-space-nowrap">
                    [[#{status}]]:
                </label>
                <select class="form-control form-select" id="userSearchStatus"
                        onchange="ezyadmin.onUserStatusSelected();">
                    <option value="">[[#{all}]]</option>
                    <option th:each="userStatus : ${userStatuses}"
                            th:value="${userStatus}"
                            th:selected="${userStatus == userSearchStatus}">
                        [[#{${userStatus.toLowerCase()}}]]
                    </option>
                </select>
            </div>
            <div class="col-lg-3 col-md-4 page-search">
                <label for="userSearchKeyword" class="white-space-nowrap">
                    [[#{search}]]:
                </label>
                <input type="search" class="form-control" th:value="${userSearchKeyword}"
                       th:placeholder="#{keyword}" id="userSearchKeyword"
                       oninput="ezyadmin.onKeydownToSearchUser();"
                       onkeydown="ezyadmin.onKeydownToSearchUser();">
            </div>
            <div class="col-lg-3 col-md-4 page-search">
                <label for="userSearchLimit" class="white-space-nowrap">
                    [[#{limit}]]:
                </label>
                <select class="form-control" id="userSearchLimit"
                        onchange="ezyadmin.onUserSearchLimitChanged();">
                    <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="userListTable" class="table table-bordered table-hover text-nowrap align-middle-cells">
                    <thead>
                        <tr>
                            <th class="text-center pl-2p5">
                                <input type="checkbox" onclick="ezyadmin.onMultiUsersClick(this)" class="wh-1rem" />
                            </th>
                            <th class="text-center">[[#{id}]]</th>
                            <th class="white-space-nowrap text-center">[[#{avatar}]]</th>
                            <th class="white-space-nowrap">[[#{username}]]</th>
                            <th class="white-space-nowrap">[[#{email}]]</th>
                            <th class="white-space-nowrap">[[#{display_name}]]</th>
                            <th class="white-space-nowrap text-center">[[#{phone_number}]]</th>
                            <th class="white-space-nowrap text-center">[[#{status}]]</th>
                            <th class="white-space-nowrap text-center">[[#{created_at}]]</th>
                            <th class="white-space-nowrap text-center">[[#{actions}]]</th>
                        </tr>
                    </thead>
                    <tbody id="userListBody">
                    </tbody>
                </table>
            </div>
            <!-- /.card-body -->
            <div class="card-footer clearfix">
                <span>
                    <span id="userCountText">0</span>
                    [[${#strings.toLowerCase(#messages.msg('of'))}]]
                    <span id="totalUserText">0</span>
                    [[${#strings.toLowerCase(#messages.msg('users'))}]]
                </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>
<th:block layout:fragment="modals">
    <th:block th:replace="~{modals/import-users :: content}" />
    <th:block th:replace="~{fragments/prompt :: content(id='activate-user-modal', title=confirm, confirmButton=activate, closeButton=close)}" />
    <th:block th:replace="~{fragments/prompt :: content(id='archive-user-modal', title=confirm, confirmButton=archive, closeButton=close, type=delete)}" />
    <th:block th:replace="~{fragments/prompt :: content(id='delete-user-modal', title=confirm, confirmButton=delete, closeButton=close)}" />
    <th:block th:replace="~{fragments/prompt :: content(id='erase-user-modal', title=confirm, confirmButton=erase, closeButton=close, type=delete)}" />
</th:block>
<script layout:fragment="scripts" th:inline="javascript">
/*<![CDATA[*/
ezyadmin.messages.user_s = /*[[#{user_s}]]*/;
ezyadmin.messages.do_you_want_to_paction_users = /*[[#{do_you_want_to_paction_users}]]*/;
ezyadmin.messages.selected_pcount_users = /*[[#{selected_pcount_users}]]*/;
ezyadmin.userSearchKeyword = /*[[${userSearchKeyword}]]*/;
ezyadmin.userSearchStatus = /*[[${userSearchStatus}]]*/;
ezyadmin.accessibleUris['/users/{username}'] = /*[[${adminRoles.isAccessible('/users/{username}')}]]*/;
ezyadmin.accessibleUris['/users/{username}/delete'] = /*[[${adminRoles.isAccessible('/users/{username}', 'DELETE')}]]*/;
ezyadmin.accessibleUris['/users/{username}/erase'] = /*[[${adminRoles.isAccessible('/users/{username}/erase', 'DELETE')}]]*/;
ezyadmin.accessibleUris['/users/{username}/edit'] = /*[[${adminRoles.isAccessible('/users/{username}/edit')}]]*/;
ezyadmin.accessibleUris['/api/v1/users/{username}/activate'] = /*[[${adminRoles.isAccessible('/api/v1/users/{username}/activate', 'PUT')}]]*/;
ezyadmin.accessibleUris['/api/v1/users/{username}/archive'] = /*[[${adminRoles.isAccessible('/api/v1/users/{username}/archive', 'PUT')}]]*/;
ezyadmin.accessibleUris['/api/v1/users/{username}/block'] = /*[[${adminRoles.isAccessible('/api/v1/users/{username}/block', 'PUT')}]]*/;
/*]]>*/

ezyadmin.userIdChecks = {}
ezyadmin.userSearchLimit = 30;

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

// ========== user search =============
ezyadmin.onKeydownToSearchUser = function() {
    var before = ezyadmin.userSearchKeyword;
    ezyadmin.userSearchKeyword = $('#userSearchKeyword').val();
    if(event.key === 'Enter' || (before && !ezyadmin.userSearchKeyword)) {
        ezyadmin.fetchUserList();
        ezyadmin.changeBrowserUrl();
    }
}

ezyadmin.onUserStatusSelected = function() {
    ezyadmin.userSearchStatus = $('#userSearchStatus').val();
    ezyadmin.fetchUserList();
    ezyadmin.changeBrowserUrl();
}

ezyadmin.onUserSearchLimitChanged = function() {
    ezyadmin.userSearchLimit = $('#userSearchLimit').val();
    ezyadmin.fetchUserList();
    ezyadmin.changeBrowserUrl();
}

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

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

// ========== user list =============
ezyadmin.fetchUserList = function(action) {
    var queryString = '';
    var limit = ezyadmin.userSearchLimit || 12;
    if (ezyadmin.userSearchKeyword) {
        queryString += '&keyword=' + ezyadmin.userSearchKeyword;
    }
    if (ezyadmin.userSearchStatus) {
        queryString += '&userStatus=' + ezyadmin.userSearchStatus;
    }
    if (action == 'current') {
        if (ezyadmin.lastUserQueryString) {
            queryString = ezyadmin.lastUserQueryString;
        }
    } else if (action == 'next') {
        if (ezyadmin.lastUserPageToken.next) {
            queryString += '&nextPageToken=' + ezyadmin.lastUserPageToken.next;
        } else {
            return;
        }
    } else if (action == 'prev') {
        if (ezyadmin.lastUserPageToken.prev) {
            queryString += '&prevPageToken=' + ezyadmin.lastUserPageToken.prev;
        } else {
            return;
        }
    } else if (action == 'last') {
        queryString += '&lastPage=true';
    }
    $.ajax({
        url: '/api/v1/users?limit=' + limit + queryString,
        type: 'GET',
        dataType: 'json'
    })
    .done(function(data) {
        $('#userCountText').text(data.count);
        $('#totalUserText').text(ezyadmin.formatTotalResults(data.total));
        ezyadmin.lastUserQueryString = queryString;
        ezyadmin.lastUserPageToken = data.pageToken;
        $('#userListBody').html(ezyadmin.buildUserListBodyHtml(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.buildUserListBodyHtml = function(users) {
    var html = '';
    users.forEach((user) => {
        html += ezyadmin.buildUserListItemHtml(user);
    });
    return html;
}
ezyadmin.buildUserListItemHtml = function(user) {
    var statusColor = ezyadmin.getTextColorByStatus(user.status);
    var html = `
        <tr>
            <td class="px-3">
                <input name="userIds"
                       type="checkbox"
                       value="${user.id}"
                       onclick="ezyadmin.onUserCheckChange(this)"
                       ${ezyadmin.userIdChecks[user.id] ? 'checked' : ''}
                       class="wh-1rem">
            </td>
            <td class="text-center">${user.id}</td>
            <td class="text-center">
    `;
    if (user.avatar) {
        html += `
            <img class="common-avatar-img" src="${ezyadmin.extractMediaUrl(user.avatar)}">
        `;
    }
    html += `
            </td>
            <td>
                <a href="/users/${user.username}${ezyadmin.lang ? `?lang=${ezyadmin.lang}` : ''}">
                    ${user.username}
                </a>
            </td>
            <td><a href="mailto:${user.email}">${user.email || ''}</a></td>
            <td>${user.displayName || ''}</td>
            <td class="text-center"><a href="tel:${user.phone}">${user.phone || ''}</a></td>
            <td class="text-center ${statusColor}">${ezyadmin.getI18nMessage(user.status.toLowerCase())}</td>
            <td class="text-center">${ezyadmin.formatTimeStamp(user.createdAt)}</td>
            <td class="text-center">
                ${ezyadmin.accessibleUris['/users/{username}'] ? `
                    <a class="btn btn-link pr-1" href="/users/${user.username}${ezyadmin.lang ? `?lang=${ezyadmin.lang}` : ''}">
                        <i class="fas fa-eye text-info"></i>
                    </a>
                ` : ''}
                ${ezyadmin.accessibleUris['/users/{username}/edit'] ? `
                    <button class="btn btn-link px-1" onclick="ezyadmin.editUser('${user.username}')">
                        <i class="fas fa-edit text-primary"></i>
                    </button>
                ` : ''}
                ${user.status === 'ACTIVATED' && ezyadmin.accessibleUris['/api/v1/users/{username}/archive'] ? `
                    <button class="btn btn-link px-1" onclick="ezyadmin.archiveUser('${user.username}')">
                        <i class="fas fa-archive text-danger"></i>
                    </button>
                ` : ''}
                ${user.status === 'ACTIVATED' && ezyadmin.accessibleUris['/api/v1/users/{username}/block'] ? `
                    <button class="btn btn-link px-1" onclick="ezyadmin.blockUser('${user.username}')">
                        <i class="fas fa-ban text-danger"></i>
                    </button>
                ` : ''}
                ${user.status !== 'ACTIVATED' && ezyadmin.accessibleUris['/api/v1/users/{username}/activate'] ? `
                    <button class="btn btn-link px-1" onclick="ezyadmin.activateUser('${user.username}')">
                        <i class="fas fa-location-arrow text-success"></i>
                    </button>
                ` : ''}
                ${user.status !== 'DELETED' && ezyadmin.accessibleUris['/users/{username}/erase'] ? `
                    <button class="btn btn-link px-1" onclick="ezyadmin.onEraseUserClick('${user.username}')">
                        <i class="fas fa-eraser text-danger"></i>
                    </button>
                ` : ''}
                ${ezyadmin.accessibleUris['/users/{username}/delete'] ? `
                    <button class="btn btn-link pl-1" onclick="ezyadmin.onDeleteUserClick('${user.username}')">
                        <i class="fas fa-trash text-danger"></i>
                    </button>
                ` : ''}
            </td>
        </tr>
        `;
	return html;
}
ezyadmin.fetchUserList();

// ============== user actions =============
ezyadmin.editUser = function(username) {
    window.location = '/users/' + username + '/edit'
        + (ezyadmin.lang ? '?lang=' + ezyadmin.lang : '');
}

// =============== do users actions ========
ezyadmin.onMultiUsersClick = function(e) {
    var checked = $(e).prop('checked');
    $('input[name="userIds"]').each(function() {
        var checkbox = $(this);
        var userId = parseInt(checkbox.val());
        ezyadmin.userIdChecks[userId] = checked;
        checkbox.prop('checked', checked);
    });
    ezyadmin.showOrHideSelectedUsersCount();
}

ezyadmin.onUserCheckChange = function(checkbox) {
    var userId = parseInt(checkbox.value);
    ezyadmin.userIdChecks[userId] = checkbox.checked;
    ezyadmin.showOrHideSelectedUsersCount();
}

ezyadmin.showOrHideSelectedUsersCount = function() {
    var count = 0;
    Object.values(ezyadmin.userIdChecks).forEach((checked) => {
        if (checked) {
            ++count;
        }
    });
    if (count) {
        $('.selected-user-count')
            .text(ezyadmin.messages.selected_pcount_users.replace('{0}', count))
            .removeClass('d-none');
    } else {
        $('.selected-user-count').addClass('d-none');
    }
}

ezyadmin.performUserBulkAction = function() {
    var action = $('#userBulkAction').val();
    if (!action) {
        return;
    }
    if (action == 'IMPORT_USERS_FROM_FILE') {
        ezyadmin.showImportUsersModel();
        return;
    }
    var actionLowerCase = action.toLowerCase();
    var actionText = ezyadmin.messages[actionLowerCase].toLowerCase();
    $('#' + actionLowerCase + '-user-modal-body-content').text(
        ezyadmin.messages.do_you_want_to_paction_users.replace('{0}', actionText)
    );
    ezyadmin.showingUserActionModel = $('#' + actionLowerCase + '-user-modal');
    ezyadmin.showingUserActionModel.modal('show');
}

ezyadmin.onPromptUserBulkActionConfirmed = function(modalId) {
    if (modalId == 'archive-user-modal') {
        ezyadmin.doUserBulkAction('archive');
    } else if (modalId == 'activate-user-modal') {
        ezyadmin.doUserBulkAction('activate');
    } else if (modalId == 'erase-user-modal') {
        ezyadmin.doUserBulkAction('erase');
    } else if (modalId == 'delete-user-modal') {
        ezyadmin.doUserBulkAction('delete');
    }
}

ezyadmin.doUserBulkAction = function(action) {
    var userIds = [];
    Object.entries(ezyadmin.userIdChecks).forEach(([key, value]) => {
        if (value) {
            userIds.push(key);
        }
    });
    if (userIds.length == 0) {
        return;
    }
    var type = 'PUT';
    var url = '/api/v1/users/' + action;
    if (action == 'erase' || action == 'delete') {
        type = 'DELETE';
    }
    if (action == 'delete') {
        url = '/api/v1/users';
    }
    url += '?ids=' + userIds.join(',');
    $.ajax({
        type: type,
        url: url,
        contentType: 'application/json'
    }).done(function () {
        ezyadmin.fetchUserList('current');
        ezyadmin.showingUserActionModel.modal('hide');
    }).fail(function (msg) {
        var errorBody;
        if (msg.responseJSON && msg.responseJSON.permission == 'denied') {
            errorBody = ezyadmin.messages.permission_denied;
        }
        ezyadmin.shortToast(
            'bg-danger',
            (ezyadmin.messages[action] || ezyadmin.toDisplayString(action)) +
                ' ' + ezyadmin.messages.user_s.toLowerCase() + ' ' +
                ezyadmin.messages.failed.toLowerCase(),
            errorBody
        );
    });
}
</script>
<th:block layout:fragment="post-scripts">
    <th:block th:replace="~{users/scripts :: update}" />
    <th:block th:replace="~{modals/import-users :: scripts}" />
</th:block>
<script layout:fragment="final-scripts">
ezyadmin.onPromptConfirmed = function(modalId) {
    if (ezyadmin.selectedUsername) {
        ezyadmin.onPromptUserActionConfirmed(modalId);
        ezyadmin.selectedUsername = '';
    } else {
        ezyadmin.onPromptUserBulkActionConfirmed(modalId);
    }
}
</script>
</body>
</html>
