<!--
 ~ 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 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-12 table-responsive bg-white" id="inboxLettersForm">
        <table 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" th:text="${totalLetter}">100</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 = {}

// ========== letter pagination =============
$('#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 = '';
    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=12' + queryString,
        type: 'GET',
        dataType: 'json'
    })
    .done(function(data) {
        $('#letterCountText').text(data.count);
        $('#totalLetterText').text(ezyadmin.formatNumberWithCommas(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="responsive-cell" style="width:80%;">
                <span>
                    ${ezyadmin.wrapTextIfNeed(letter.title, 'strong', !letter.readAt)} - ${letter.content}
                </span>
            </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>
