<!--
 ~ 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">
<body>
<script th:fragment="avatar" th:inline="javascript">
/*<![CDATA[*/
ezyadmin.messages.update_avatar_failed = /*[[#{update_avatar_failed}]]*/;
ezyadmin.messages.update_cover_image_failed = /*[[#{update_cover_image_failed}]]*/;
/*]]>*/
// ============== media ========
ezyadmin.selectAdminAvatarImage = function() {
    ezyadmin
        .showMediaModal("avatarImage")
        .onMediaSelected(ezyadmin.updateAdminAvatar);
}

ezyadmin.selectAdminCoverImage = function() {
    ezyadmin
        .showMediaModal("coverImage")
        .onMediaSelected(ezyadmin.updateAdminCoverImage);
}

// ============== avatar ========
ezyadmin.updateAdminAvatar = function(media) {
    $.ajax({
        type: "PUT",
        url: '/api/v1/admins/me/update-avatar',
        data: {avatarId: media.id},
        success: function (data) {
            $('#mainAdminAvatar')
                .attr('src', ezyadmin.extractMediaUrl(media))
                .removeClass('d-none');
            $('#mainAdminAvatarTmp').addClass('d-none');
            $('#adminAvatarImage')
                .attr('src', ezyadmin.extractMediaUrl(media))
                .removeClass('d-none');
            $('#mainAdminAvatarContainer').removeClass('d-none');
            $('#adminAvatarImageTmp').addClass('d-none');
            ezyadmin.closeMediaModal();
        },
        error: function (data, e) {
            ezyadmin.shortToast(
                'bg-danger',
                ezyadmin.messages.update_avatar_failed + '!'
            );
        }
    });
}

// ============== cover ========
ezyadmin.updateAdminCoverImage = function(media) {
    $.ajax({
        type: "PUT",
        url: '/api/v1/admins/me/update-cover-image',
        data: {coverImageId: media.id},
        success: function (data) {
            $('#mainAdminCoverImage')
                .attr('src', ezyadmin.extractMediaUrl(media))
                .removeClass('d-none');
            $('#adminCoverImage')
                .attr('src', ezyadmin.extractMediaUrl(media))
                .removeClass('d-none');
            $('#mainAdminCoverImageContainer').removeClass('d-none');
            $('#addAdminCoverImageButton').addClass('d-none');
            ezyadmin.closeMediaModal();
        },
        error: function (data, e) {
            ezyadmin.shortToast(
                'bg-danger',
                ezyadmin.messages.update_cover_image_failed + '!'
            );
        }
    });
}
</script>
<script th:fragment="add-edit">
ezyadmin.addOrEditAdmin = function(action) {
    var url = '/api/v1/admins/add';
    var formData = ezyadmin.formDataToObject(action + 'AdminForm');
    var roleIds = formData.roleIds;
    var isMeAdmin = ezyadmin.selectedAdminUsername == ezyadmin.adminUsername;
    if (action == 'add') {
        var readyToSubmit = true;
        var password = $('input[name="password"]');
        var retypePassword = $('input[name="retypePassword"]');

        if (password.val() === retypePassword.val()) {
            password.removeClass('is-invalid');
            retypePassword.removeClass('is-invalid');
            $('retypePasswordErrorLabel').removeClass('d-none');
        } else {
            password.addClass('is-invalid');
            retypePassword.addClass('is-invalid');
            $('retypePasswordErrorLabel').addClass('d-none');
            readyToSubmit = false;
        }
        if (!readyToSubmit) {
            return;
        }
    } else {
        url = isMeAdmin
            ? '/api/v1/admins/me'
            : '/api/v1/admins/' + ezyadmin.selectedAdminUsername;
    }
    ezyadmin.showLoadingScreen();
    $.ajax({
        type: action == 'add' ? 'POST' : 'PUT',
        url: url,
        data: JSON.stringify(formData),
        contentType: 'application/json',
        success: function (data) {
            if (action == 'add') {
                window.location = '/admins/' + data.username
                    + (ezyadmin.lang ? '?lang=' + ezyadmin.lang : '');
            } else {
                var callback = () => {
                    window.location = '/admins/'
                        + (isMeAdmin ? 'me' : ezyadmin.selectedAdminUsername)
                        + (ezyadmin.lang ? '?lang=' + ezyadmin.lang : '');
                };
                if (formData.roleIds) {
                    ezyadmin.updateAdminRoles(formData.roleIds, callback);
                } else {
                    callback();
                }
            }
        },
        error: function (data, e) {
            ezyadmin.hideLoadingScreen();
            ezyadmin.processUpdateApiErrors(formData, data);
        }
    });
};

ezyadmin.updateAdminRoles = function(roleIds, callback) {
    var formData = {
        roleIds: roleIds
    };
    var url = ezyadmin.selectedAdminUsername == ezyadmin.adminUsername
            ? '/api/v1/admins/me'
            : '/api/v1/admins/' + ezyadmin.selectedAdminUsername;
    url += '/roles';
    $.ajax({
        type: 'PUT',
        url: url,
        data: JSON.stringify(formData),
        contentType: 'application/json',
        success: function (data) {
            callback();
        },
        error: function (data, e) {
            ezyadmin.hideLoadingScreen();
            ezyadmin.processUpdateApiErrors(formData, data);
        }
    });
}
</script>
<script th:fragment="update">
ezyadmin.archiveAdmin = function(username) {
    ezyadmin.doAdminAction(username, 'archive');
}

ezyadmin.activateAdmin = function(username) {
    ezyadmin.doAdminAction(username, 'activate');
}

ezyadmin.doAdminAction = function(username, action) {
    $.ajax({
        type: 'PUT',
        url: '/api/v1/admins/' + username + '/' + action,
        contentType: 'application/json'
    }).done(function () {
        if (ezyadmin.onAfterAdminAction) {
            ezyadmin.onAfterAdminAction(action);
        } else if (ezyadmin.fetchAdminList) {
            ezyadmin.fetchAdminList('current');
        } else {
            location.reload();
        }
    }).fail(function (msg) {
        var errorBody;
        if (msg.responseJSON && msg.responseJSON.permission == 'denied') {
            errorBody = ezyadmin.messages.permission_denied;
        }
        ezyadmin.shortToast('bg-danger', ezyadmin.toDisplayString(action) + ' ' + username + ' failed', errorBody);
    });
}
</script>
</body>
</html>
