<!--
 ~ 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:th="http://www.thymeleaf.org">
<body>
<th:block th:fragment="content">
    <div class="col-12">
        <hr class="mb-4" />
    </div>
    <div class="col-12">
        <h3>[[#{activity_history}]]</h3>
    </div>
    <div class="col-12">
        <div class="row">
            <div class="col-lg-3 col-md-4 page-search">
                <label for="adminActivitySearchKeyword" class="text-nowrap">[[#{search}]]: </label>
                <input type="search" class="form-control"
                       th:placeholder="#{keyword}"
                       id="adminActivitySearchKeyword"
                       oninput="ezyadmin.onKeydownToSearchAdminActivity(this);"
                       onkeydown="ezyadmin.onKeydownToSearchAdminActivity(this);">
            </div>
            <div class="col-lg-3 col-md-4 page-search">
                <label for="adminActivitySearchHttpMethod" class="text-nowrap">[[#{method}]]: </label>
                <select class="form-control form-select" id="adminActivitySearchHttpMethod"
                        onchange="ezyadmin.onAdminActivitySearchHttpMethodChanged(this);">
                    <option value="">[[#{all}]]</option>
                    <option th:each="httpMethod : ${httpMethods}"
                            th:value="${httpMethod}">
                        [[${httpMethod}]]
                    </option>
                </select>
            </div>
            <div class="col-lg-3 col-md-4 page-search">
                <label for="adminActivitySearchUriType" class="text-nowrap">[[#{type}]]: </label>
                <select class="form-control form-select" id="adminActivitySearchUriType"
                        onchange="ezyadmin.onAdminActivitySearchUriTypeChanged(this);">
                    <option value="">[[#{all}]]</option>
                    <option value="API">API</option>
                    <option value="VIEW">VIEW</option>
                </select>
            </div>
            <div class="col-lg-3 col-md-4 page-search">
                <label for="adminActivitySearchTimeRangePicker" class="text-nowrap">[[#{time_range}]]: </label>
                <input type="text" class="form-control"
                       id="adminActivitySearchTimeRangePicker"/>
            </div>
            <div class="col-lg-3 col-md-4 page-search">
                <label for="adminActivitySearchLimit" class="white-space-nowrap">
                    [[#{limit}]]:
                </label>
                <select class="form-control" id="adminActivitySearchLimit"
                        onchange="ezyadmin.onAdminActivitySearchLimitChanged(this);">
                    <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="400">400 [[#{item_s}]]</option>
                    <option value="500">500 [[#{item_s}]]</option>
                </select>
            </div>
        </div>
    </div>
    <div class="col-12">
        <div class="card">
            <div class="card-body table-responsive p-0">
                <table id="adminActivityListTable" class="table table-bordered table-hover text-nowrap align-middle-cells">
                    <thead>
                    <tr>
                        <th class="text-center pl-2p5">#</th>
                        <th class="text-center">[[#{time}]]</th>
                        <th class="text-center">[[#{method}]]</th>
                        <th>[[#{uri}]]</th>
                        <th class="text-center">[[#{type}]]</th>
                        <th class="text-center">[[#{feature}]]</th>
                        <th>[[#{parameters}]]</th>
                    </tr>
                    </thead>
                    <tbody id="adminActivityListBody">
                    </tbody>
                </table>
            </div>
            <!-- /.card-body -->
            <div class="card-footer clearfix">
                <span><span id="adminActivityCountText">0</span>
                    [[${#strings.toLowerCase(#messages.msg('of'))}]]
                    <span id="totalAdminActivityText">0</span>
                    [[${#strings.toLowerCase(#messages.msg('activities'))}]]
                </span>
                <ul class="pagination pagination-sm m-0 float-right">
                    <li class="page-item">
                        <button class="page-link" id="firstPageButton">
                            <i class="fas fa-arrow-circle-left pl-1 pr-1"></i>
                        </button>
                    </li>
                    <li class="page-item">
                        <button class="page-link" id="prevPageButton">[[#{prev}]]</button>
                    </li>
                    <li class="page-item">
                        <button class="page-link" id="nextPageButton">[[#{next}]]</button>
                    </li>
                    <li class="page-item">
                        <button class="page-link" id="lastPageButton">
                            <i class="fas fa-arrow-circle-right pl-1 pr-1"></i>
                        </button>
                    </li>
                </ul>
            </div>
            <!-- /.card-footer -->
        </div>
    </div>
</th:block>
<script th:fragment="scripts" th:inline="javascript">
/*<![CDATA[*/
ezyadmin.accessibleUris['/api/v1/admins/{adminId}/activities'] = /*[[${adminRoles.isAccessible('/api/v1/admins/{adminId}/activities')}]]*/;
/*]]>*/

// ========== admin activity =============
ezyadmin.onKeydownToSearchAdminActivity = function(e) {
    var before = ezyadmin.adminActivitySearchKeyword;
    ezyadmin.adminActivitySearchKeyword = $(e).val();
    if(event.key === 'Enter' || (before && !ezyadmin.adminActivitySearchKeyword)) {
        ezyadmin.fetchAdminActivityList();
    }
}

ezyadmin.onAdminActivitySearchHttpMethodChanged = function(e) {
    ezyadmin.adminActivitySearchHttpMethod = $(e).val();
    ezyadmin.fetchAdminActivityList();
}

ezyadmin.onAdminActivitySearchUriTypeChanged = function(e) {
    ezyadmin.adminActivitySearchUriType = $(e).val();
    ezyadmin.fetchAdminActivityList();
}

ezyadmin.onAdminActivitySearchLimitChanged = function(e) {
    ezyadmin.adminActivitySearchLimit = $(e).val();
    ezyadmin.fetchAdminActivityList();
}

$(document).ready(() => {
    ezyadmin.createDateRangePicker(
        '#adminActivitySearchTimeRangePicker',
        {},
        function(start, end, label) {
            ezyadmin.adminActivitySearchCreatedAtStartInclusive = start.unix() * 1000;
            ezyadmin.adminActivitySearchCreatedAtEndInclusive = end.unix() * 1000;
            ezyadmin.fetchAdminActivityList();
        }
    );
    $('#adminActivitySearchTimeRangePicker').on('cancel.daterangepicker', function (ev, picker) {
        ezyadmin.adminActivitySearchCreatedAtStartInclusive = 0;
        ezyadmin.adminActivitySearchCreatedAtEndInclusive = 0;
        ezyadmin.fetchAdminActivityList();
    });
});

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

// ========== admin activity list =============
ezyadmin.fetchAdminActivityList = function(action) {
    ezyadmin.showLoadingScreen();
    var queryString = '';
    if (ezyadmin.adminActivitySearchKeyword) {
        queryString += '&keyword=' + ezyadmin.adminActivitySearchKeyword;
    }
    if (ezyadmin.adminActivitySearchHttpMethod) {
        queryString += '&method=' + ezyadmin.adminActivitySearchHttpMethod;
    }
    if (ezyadmin.adminActivitySearchUriType) {
        queryString += '&uriType=' + ezyadmin.adminActivitySearchUriType;
    }
    if (ezyadmin.adminActivitySearchCreatedAtStartInclusive) {
        queryString += '&createdAtStartInclusive=' + ezyadmin.adminActivitySearchCreatedAtStartInclusive;
    }
    if (ezyadmin.adminActivitySearchCreatedAtEndInclusive) {
        queryString += '&createdAtEndInclusive=' + ezyadmin.adminActivitySearchCreatedAtEndInclusive;
    }
    if (action == 'next') {
        if (ezyadmin.lastAdminActivityPageToken.next) {
            queryString += '&nextPageToken=' + ezyadmin.lastAdminActivityPageToken.next;
        } else {
            return;
        }
    } else if (action == 'prev') {
        if (ezyadmin.lastAdminActivityPageToken.prev) {
            queryString += '&prevPageToken=' + ezyadmin.lastAdminActivityPageToken.prev;
        } else {
            return;
        }
    } else if (action == 'last') {
        queryString += '&lastPage=true';
    }
    var requestUri = ezyadmin.adminIsMe
        ? '/api/v1/admins/me/activities'
        : '/api/v1/admins/' + ezyadmin.selectedAdminId + '/activities';
    var limit = ezyadmin.adminActivitySearchLimit || 30;
    $.ajax({
        url: requestUri + '?limit=' + limit + queryString,
        type: 'GET',
        dataType: 'json'
    })
    .done(function(data) {
        ezyadmin.hideLoadingScreen();
        $('#adminActivityCountText').text(data.count);
        $('#totalAdminActivityText').text(ezyadmin.formatTotalResults(data.total));
        ezyadmin.lastAdminActivityPageToken = data.pageToken;
        $('#adminActivityListBody').html(ezyadmin.buildAdminActivityListBodyHtml(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.hideLoadingScreen();
        ezyadmin.processGetApiErrors(e);
    });
}

ezyadmin.buildAdminActivityListBodyHtml = function(adminActivities) {
    var html = '';
    adminActivities.forEach((adminActivity) => {
        html += ezyadmin.buildAdminActivityListItemHtml(adminActivity);
    });
    return html;
}
ezyadmin.buildAdminActivityListItemHtml = function(adminActivity) {
    var statusColor = ezyadmin.getTextColorByStatus(adminActivity.status);
    var html = `
        <tr>
            <td class="text-center pl-2p5">${ezyadmin.formatNumberWithCommas(adminActivity.id)}</td>
            <td class="text-center">${ezyadmin.formatTimeStamp(adminActivity.createdAt)}</td>
            <td class="text-center">${adminActivity.method}</td>
            <td>${adminActivity.uri}</td>
            <td class="text-center">${adminActivity.uriType}</td>
            <td class="text-center">${adminActivity.feature || ''}</td>
            <td class="text-wrap text-break">${adminActivity.parameters || ''}</td>
        </tr>
        `;
    return html;
}
ezyadmin.fetchAdminActivityList();
</script>
</body>
</html>
