<!--
 ~ 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">
        <div class="row">
            <div class="col-lg-3"></div>
            <div class="col-lg-3 col-md-4 page-search">
                <label for="settingSearchDataType" class="white-space-nowrap d-md-block d-none">
                    [[#{type}]]:
                </label>
                <select class="form-control form-select" id="settingSearchDataType"
                        onchange="ezyadmin.onSettingStatusSelected();">
                    <option value="">[[#{all}]]</option>
                    <option th:each="dataType : ${dataTypes}"
                            th:value="${dataType}"
                            th:selected="${dataType == settingSearchDataType}">
                        [[#{${dataType.toString().toLowerCase()}}]]
                    </option>
                </select>
            </div>
            <div class="col-lg-3 col-md-4 page-search">
                <label for="settingSearchKeyword" class="white-space-nowrap d-md-block d-none">
                    [[#{search}]]:
                </label>
                <input type="search" class="form-control" th:value="${settingSearchKeyword}"
                       th:placeholder="#{keyword}" id="settingSearchKeyword"
                       oninput="ezyadmin.onKeydownToSearchSetting();"
                       onkeydown="ezyadmin.onKeydownToSearchSetting();">
            </div>
            <div class="col-lg-3 col-md-4 page-search">
                <label for="settingSearchLimit" class="white-space-nowrap d-md-block d-none">
                    [[#{limit}]]:
                </label>
                <select class="form-control" id="settingSearchLimit"
                        onchange="ezyadmin.onSettingSearchLimitChanged();">
                    <option value="12" selected>12 [[#{item_s}]]</option>
                    <option value="30">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-12">
        <div class="card">
            <div class="card-body table-responsive p-0">
                <table id="settingListTable" class="table table-bordered table-hover align-middle-cells">
                    <thead>
                    <tr>
                        <th class="text-center pl-2p5">
                            <input type="checkbox" onclick="ezyadmin.onMultiSettingsClick(this)" class="wh-1rem" />
                        </th>
                        <th class="text-center pl-2p5">#</th>
                        <th>[[#{name}]]</th>
                        <th>[[#{value}]]</th>
                        <th class="text-center">[[#{type}]]</th>
                        <th class="text-center">[[#{updated_at}]]</th>
                        <th class="text-center">[[#{actions}]]</th>
                    </tr>
                    </thead>
                    <tbody id="settingListBody">
                    </tbody>
                </table>
            </div>
            <!-- /.card-body -->
            <div class="card-footer clearfix">
                <span>
                    <span id="settingCountText">0</span>
                    [[${#strings.toLowerCase(#messages.msg('of'))}]]
                    <span id="totalSettingText">0</span>
                    [[${#strings.toLowerCase(#messages.msg('settings'))}]]
                </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>
</th:block>
<script th:fragment="scripts" th:inline="javascript">
/*<![CDATA[*/
ezyadmin.settingSearchDataType = /*[[${settingSearchDataType}]]*/ '';
ezyadmin.settingSearchKeyword = /*[[${settingSearchKeyword}]]*/ '';
/*]]>*/

ezyadmin.settingSearchLimit = 12;

// ========== setting search =============
ezyadmin.onKeydownToSearchSetting = function() {
    ezyadmin.settingSearchKeyword = $('#settingSearchKeyword').val();
    if(event.key === 'Enter' || !ezyadmin.settingSearchKeyword) {
        ezyadmin.fetchSettingList();
        ezyadmin.changeBrowserUrl();
    }
}

ezyadmin.onSettingStatusSelected = function() {
    ezyadmin.settingSearchDataType = $('#settingSearchDataType').val();
    ezyadmin.fetchSettingList();
    ezyadmin.changeBrowserUrl();
}

ezyadmin.onSettingSearchLimitChanged = function() {
    ezyadmin.settingSearchLimit = $('#settingSearchLimit').val();
    ezyadmin.fetchSettingList();
    ezyadmin.changeBrowserUrl();
}

ezyadmin.changeBrowserUrl = function() {
    var params = [];
    if (ezyadmin.settingSearchKeyword) {
        params.push('keyword=' + ezyadmin.settingSearchKeyword);
    }
    if (ezyadmin.settingSearchDataType) {
        params.push('dataType=' + ezyadmin.settingSearchDataType);
    }
    if (ezyadmin.lang) {
        params.push('lang=' + ezyadmin.lang);
    }
    var url = location.pathname;
    if (params.length) {
        url += '?' + params.join('&');
    }
    window.history.pushState({}, '', url);
}

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

// ========== setting list =============
ezyadmin.settingById = {};
ezyadmin.settingIdChecks = {};
ezyadmin.checkedSettingIds = [];
ezyadmin.fetchSettingList = function(action) {
    var queryString = '';
    var limit = ezyadmin.settingSearchLimit || 12;
    if (ezyadmin.settingSearchKeyword) {
        queryString += '&keyword=' + ezyadmin.settingSearchKeyword;
    }
    if (ezyadmin.settingSearchDataType) {
        queryString += '&dataType=' + ezyadmin.settingSearchDataType;
    }
    if (action == 'current') {
        if (ezyadmin.lastSettingQueryString) {
            queryString = ezyadmin.lastSettingQueryString;
        }
    } else if (action == 'next') {
        if (ezyadmin.lastSettingPageToken.next) {
            queryString += '&nextPageToken=' + ezyadmin.lastSettingPageToken.next;
        } else {
            return;
        }
    } else if (action == 'prev') {
        if (ezyadmin.lastSettingPageToken.prev) {
            queryString += '&prevPageToken=' + ezyadmin.lastSettingPageToken.prev;
        } else {
            return;
        }
    } else if (action == 'last') {
        queryString += '&lastPage=true';
    }
    $.ajax({
        url: '/api/v1/settings?limit=' + limit + queryString,
        type: 'GET',
        dataType: 'json'
    })
    .done(function(data) {
        $('#settingCountText').text(data.count);
        $('#totalSettingText').text(ezyadmin.formatTotalResults(data.total));
        ezyadmin.lastSettingQueryString = queryString;
        ezyadmin.lastSettingPageToken = data.pageToken;
        data.items.forEach((item) => {
            ezyadmin.settingById[item.id] = item;
        });
        $('#settingListBody').html(ezyadmin.buildSettingListBodyHtml(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.buildSettingListBodyHtml = function(settings) {
    var html = '';
    settings.forEach((setting) => {
        html = html + ezyadmin.buildSettingItemHtml(setting);
    });
    return html;
}

ezyadmin.buildSettingItemHtml = function(setting) {
    var html = `
        <tr id="settingItem${setting.id}">
            <td class="px-3">
                <input name="settingIds"
                       type="checkbox"
                       value="${setting.id}"
                       onclick="ezyadmin.onSettingCheckChange(this)"
                       ${ezyadmin.settingIdChecks[setting.id] ? 'checked' : ''}
                       class="wh-1rem">
            </td>
            <td class="text-center pl-2p5">${setting.id}</td>
            <td>
                <button type="button" class="btn btn-link" onclick="ezyadmin.openSettingModal(${setting.id})">
                    ${setting.name}
                </button>
            </td>
            <td class="text-wrap line-break-anywhere min-width-250-px">
                ${setting.value || ''}
            </td>
            <td class="text-center">${ezyadmin.getI18nMessage(setting.dataType.toLowerCase())}</td>
            <td class="text-center">${ezyadmin.formatTimeStamp(setting.updatedAt)}</td>
            <td class="text-center">
                <button type="button" class="btn btn-link" onclick="ezyadmin.openSettingModal(${setting.id})">
                    <i class="fas fa-edit text-primary"></i>
                </button>
            </td>
        </tr>
    `;
    return html;
}

ezyadmin.fetchSettingList();

// =============== do settings actions ========
ezyadmin.onMultiSettingsClick = function(e) {
    var checked = $(e).prop('checked');
    ezyadmin.checkedSettingIds = [];
    $('input[name="settingIds"]').each(function() {
        var checkbox = $(this);
        var settingId = parseInt(checkbox.val());
        ezyadmin.settingIdChecks[settingId] = checked;
        checkbox.prop('checked', checked);
        if (checked) {
            ezyadmin.checkedSettingIds.push(settingId);
        }
    });
    ezyadmin.updateTaggableEntityFromCheckedSettingIds();
}

ezyadmin.onSettingCheckChange = function(checkbox) {
    var settingId = parseInt(checkbox.value);
    ezyadmin.settingIdChecks[settingId] = checkbox.checked;
    if (checkbox.checked) {
        if (ezyadmin.checkedSettingIds.indexOf(settingId) < 0) {
            ezyadmin.checkedSettingIds.push(settingId);
        }
    } else {
        ezyadmin.removeItemFromList(ezyadmin.checkedSettingIds, settingId);
    }
    ezyadmin.updateTaggableEntityFromCheckedSettingIds();
}

ezyadmin.updateTaggableEntityFromCheckedSettingIds = function() {
    if (!ezyadmin.checkedSettingIds.length) {
        ezyadmin.taggableEntity = null;
        return;
    }
    var lastCheckedSettingId = ezyadmin.checkedSettingIds[ezyadmin.checkedSettingIds.length - 1];
    var setting = ezyadmin.settingById[lastCheckedSettingId];
    if (!setting) {
        return;
    }
    ezyadmin.taggableEntity = {
        id: setting.id,
        code: setting.name,
        displayName: setting.name,
        type: 'ezy_settings'
    };
}
</script>
</body>
</html>
