<!--
 ~ 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}">
<head>
    <style>
        .read-letter strong {
            font-weight: normal;
        }
    </style>
</head>
<body>
<div layout:fragment="content" class="row">
    <div class="col-12 mb-2 selected-letter-count d-none"></div>
    <div class="col-12 mb-3">
        <div class="d-flex align-items-center justify-content-between">
            <div class="d-flex align-items-center">
                <button class="btn btn-link" onclick="ezyadmin.readSelectedLetters();">
                    <i class="fas fa-envelope-open-text"></i> [[#{mark_as_read}]]
                </button>
                <button class="btn btn-link text-danger" onclick="ezyadmin.deleteLetters();">
                    <i class="fas fa-trash"></i> [[#{delete}]]
                </button>
            </div>
            <div class="col-lg-3 col-md-4">
                <div class="d-flex align-items-center gap-2">
                    <label for="letterSearchLimit" class="white-space-nowrap mb-0">
                        [[#{limit}]]:
                    </label>
                    <select class="form-control" id="letterSearchLimit"
                            onchange="ezyadmin.onLetterSearchLimitChanged();">
                        <option value="12" selected>12 [[#{item_s}]]</option>
                        <option value="24">24 [[#{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>
    <div class="col-12 table-responsive bg-white" id="inboxLettersForm">
        <table id="letterListTable" class="table table-hover text-nowrap">
            <thead>
                <tr>
                    <th>
                        <input type="checkbox" onclick="ezyadmin.onMultiLettersClick(this)" class="wh-1rem" />
                    </th>
                    <th>[[#{from}]]</th>
                    <th>[[#{title}]]</th>
                    <th>[[#{time}]]</th>
                </tr>
            </thead>
            <tbody id="letterListBody">
            </tbody>
        </table>
    </div>
    <div class="col-12 mt-3 mb-5">
         <span><span id="letterCountText">1</span>
            [[${#strings.toLowerCase(#messages.msg('of'))}]]
            <span id="totalLetterText">0</span>
            [[${#strings.toLowerCase(#messages.msg('items'))}]]
        </span>
        <ul class="pagination pagination-sm m-0 float-right">
            <li class="page-item cursor-pointer">
                <a class="page-link" id="firstPageButton">
                    <i class="fas fa-arrow-circle-left pl-1 pr-1"></i>
                </a>
            </li>
            <li class="page-item cursor-pointer">
                <a class="page-link" id="prevPageButton">[[#{prev}]]</a>
            </li>
            <li class="page-item cursor-pointer">
                <a class="page-link" id="nextPageButton">[[#{next}]]</a>
            </li>
            <li class="page-item cursor-pointer">
                <a class="page-link" id="lastPageButton">
                    <i class="fas fa-arrow-circle-right pl-1 pr-1"></i>
                </a>
            </li>
        </ul>
    </div>
</div>
<script layout:fragment="scripts" th:inline="javascript">
/*<![CDATA[*/
ezyadmin.messages.administrator = /*[[#{administrator}]]*/;
ezyadmin.messages.selected_pcount_letters = /*[[#{selected_pcount_letters}]]*/;
/*]]>*/
ezyadmin.letterIdChecks = {}
ezyadmin.letterSearchLimit = 12;

// ========== letter pagination =============
ezyadmin.onLetterSearchLimitChanged = function() {
    ezyadmin.letterSearchLimit = $('#letterSearchLimit').val();
    ezyadmin.fetchLetterList();
}
$('#firstPageButton').click(() => {
    ezyadmin.fetchLetterList('first');
});
$('#lastPageButton').click(() => {
    ezyadmin.fetchLetterList('last');
});
$('#nextPageButton').click(() => {
    ezyadmin.fetchLetterList('next');
});
$('#prevPageButton').click(() => {
    ezyadmin.fetchLetterList('prev');
});

// ========== letter list =============
ezyadmin.fetchLetterList = function(action) {
    var queryString = '';
    var limit = ezyadmin.letterSearchLimit || 12;
    if (action == 'next') {
        if (ezyadmin.lastLetterPageToken.next) {
            queryString += '&nextPageToken=' + ezyadmin.lastLetterPageToken.next;
        } else {
            return;
        }
    } else if (action == 'prev') {
        if (ezyadmin.lastLetterPageToken.prev) {
            queryString += '&prevPageToken=' + ezyadmin.lastLetterPageToken.prev;
        } else {
            return;
        }
    } else if (action == 'last') {
        queryString += '&lastPage=true';
    }
    $.ajax({
        url: '/api/v1/admins/me/letters?limit=' + limit + queryString,
        type: 'GET',
        dataType: 'json'
    })
    .done(function(data) {
        $('#letterCountText').text(data.count);
        $('#totalLetterText').text(ezyadmin.formatTotalResults(data.total));
        ezyadmin.lastLetterPageToken = data.pageToken;
        $('#letterListBody').html(
            ezyadmin.buildLetterListBodyHtml(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.buildLetterListBodyHtml = function(letters) {
    var html = '';
    letters.forEach((letter) => {
        html += ezyadmin.buildLetterListItemHtml(letter);
    });
    return html;
}

ezyadmin.buildLetterListItemHtml = function(letter) {
    var from = ezyadmin.messages.administrator;
    if (letter.fromUser) {
        from = letter.fromUser.name;
    } else if (letter.fromAdmin) {
        from = letter.fromAdmin.name;
    }
    var html = `
        <tr class="cursor-pointer" id="letter-row-${letter.id}">
            <td>
                <input name="letterIds" type="checkbox" value="${letter.id}"
                    onclick="ezyadmin.onLetterCheckChange(this)"
                    ${ezyadmin.letterIdChecks[letter.id] ? 'checked' : ''}
                    class="wh-1rem">
            </td>
            <td onclick="ezyadmin.onLetterSelected(${letter.id}, ${letter.readAt});">
                ${ezyadmin.wrapTextIfNeed(from, 'strong', !letter.readAt)}
            </td>
            <td onclick="ezyadmin.onLetterSelected(${letter.id}, ${letter.readAt});"
                class="text-wrap">
                ${ezyadmin.wrapTextIfNeed(letter.title, 'strong', !letter.readAt)} - ${letter.content}
            </td>
            <td onclick="ezyadmin.redirectToLetter(${letter.id});" class="text-right">
                ${ezyadmin.getTimeRangeTextValue(letter.sentAt, false)}
            </td>
        </tr>`;
	return html;
}

ezyadmin.fetchLetterList();

// =============== do letters actions ========
ezyadmin.onMultiLettersClick = function(e) {
    var checked = $(e).prop('checked');
    $('input[name="letterIds"]').each(function() {
        var checkbox = $(this);
        var letterId = parseInt(checkbox.val());
        ezyadmin.letterIdChecks[letterId] = checked;
        checkbox.prop('checked', checked);
    });
    ezyadmin.showOrHideSelectedLettersCount();
}

ezyadmin.onLetterCheckChange = function(checkbox) {
    var letterId = parseInt(checkbox.value);
    ezyadmin.letterIdChecks[letterId] = checkbox.checked;
    ezyadmin.showOrHideSelectedLettersCount();
}

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

ezyadmin.readSelectedLetters = function() {
    var letterIds = [];
    Object.entries(ezyadmin.letterIdChecks).forEach(([key, value]) => {
        if (value) {
            letterIds.push(parseInt(key));
        }
    });
    if (letterIds.length == 0) {
        return;
    }
    $.ajax({
        type: 'POST',
        url: '/api/v1/admins/me/letters/read',
        data: JSON.stringify({ letterIds: letterIds }),
        contentType: 'application/json',
        success: function () {
            letterIds.forEach((letterId) => {
                $('#letter-row-' + letterId).addClass('read-letter');
                $('#letter-row-' + letterId + ' input[type="checkbox"]')
                    .prop('checked', false);
            });
            ezyadmin.reloadCurrentLetterPage();
        },
        error: function (data, e) {
            ezyadmin.processUpdateApiErrors({}, data);
        }
    });
}

ezyadmin.onLetterSelected = function(letterId, readAt) {
    ezyadmin.redirectToLetter(letterId);
}

ezyadmin.redirectToLetter = function(letterId) {
    window.location = '/admins/inbox/' + letterId;
}

ezyadmin.deleteLetters = function() {
    var letterIds = [];
    Object.entries(ezyadmin.letterIdChecks).forEach(([key, value]) => {
        if (value) {
            letterIds.push(key);
        }
    });
    if (letterIds.length == 0) {
        return;
    }
    $.ajax({
        type: 'DELETE',
        url: '/api/v1/admins/me/letters?ids=' + letterIds.join(','),
        success: function () {
            letterIds.forEach((letterId) => {
                $('#letter-row-' + letterId).remove();
            });
            ezyadmin.reloadCurrentLetterPage();
        },
        error: function (data, e) {
            ezyadmin.processUpdateApiErrors({}, data);
        }
    });
}

ezyadmin.reloadCurrentLetterPage = function() {
    ezyadmin.letterIdChecks = [];
    ezyadmin.showOrHideSelectedLettersCount();
}
</script>
</body>
</html>
