<!--
 ~ 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.selectUserAvatarImage = function() {
    ezyadmin
        .showMediaModal("avatarImage")
        .onMediaSelected(ezyadmin.updateUserAvatar);
}

ezyadmin.selectUserCoverImage = function() {
    ezyadmin
        .showMediaModal("coverImage")
        .onMediaSelected(ezyadmin.updateUserCoverImage);
}

// ============== avatar ========
ezyadmin.updateUserAvatar = function(media) {
    var username = ezyadmin.selectedUsername || ezyadmin.editUserUsername;
    $.ajax({
        type: "PUT",
        url: '/api/v1/users/' + username + '/update-avatar',
        data: JSON.stringify({avatarId: media.id}),
        contentType: 'application/json',
        success: function (data) {
            $('#mainUserAvatar')
                .attr('src', ezyadmin.extractMediaUrl(media))
                .removeClass('d-none');
            $('#mainUserAvatarTmp').addClass('d-none');
            $('#userAvatarImage')
                .attr('src', ezyadmin.extractMediaUrl(media))
                .removeClass('d-none');
            $('#mainUserAvatarContainer').removeClass('d-none');
            $('#userAvatarImageTmp').addClass('d-none');
            ezyadmin.closeMediaModal();
        },
        error: function (data, e) {
            ezyadmin.shortToast(
                'bg-danger',
                ezyadmin.messages.update_avatar_failed + '!'
            );
        }
    });
}

// ============== avatar ========
ezyadmin.updateUserCoverImage = function(media) {
    var username = ezyadmin.selectedUsername || ezyadmin.editUserUsername;
    $.ajax({
        type: "PUT",
        url: '/api/v1/users/' + username + '/update-cover-image',
        data: JSON.stringify({coverImageId: media.id}),
        contentType: 'application/json',
        success: function (data) {
            $('#mainUserCoverImage')
                .attr('src', ezyadmin.extractMediaUrl(media))
                .removeClass('d-none');
            $('#userCoverImage')
                .attr('src', ezyadmin.extractMediaUrl(media))
                .removeClass('d-none');
            $('#mainUserCoverImageContainer').removeClass('d-none');
            $('#addUserCoverImageButton').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.addOrEditUser = function(action) {
    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;
        }
    }
    var formData = ezyadmin.formDataToObject(action + 'UserForm');
    var url = (action == 'add')
        ? '/api/v1/users/add'
        : '/api/v1/users/' + ezyadmin.editUserUsername;
    $.ajax({
        type: action == 'add' ? 'POST' : 'PUT',
        url: url,
        data: JSON.stringify(formData),
        contentType: 'application/json',
        success: function (data) {
            var username = action == 'add'
                ? data.username
                : ezyadmin.editUserUsername;
            ezyadmin.onUserSaved(action, username);
        },
        error: function (data, e) {
            ezyadmin.processUpdateApiErrors(formData, data);
        }
    });
};

ezyadmin.onUserSaved = function(action, username) {
    window.location = ezyadmin.createUrlWithPreviousScreenParams(
        '/users/' + username
    );
}
</script>
<script th:fragment="update" th:inline="javascript">
/*<![CDATA[*/
ezyadmin.messages.erase = /*[[#{erase}]]*/;
ezyadmin.messages.do_you_want_to_erase_user = /*[[#{do_you_want_to_erase_user}]]*/;
ezyadmin.messages.do_you_want_to_delete_user = /*[[#{do_you_want_to_delete_user}]]*/;
/*]]>*/
// ==================== archive a user ============
ezyadmin.archiveUser = function(username) {
    ezyadmin.doUserAction(username, 'archive');
}

ezyadmin.blockUser = function(username) {
    ezyadmin.doUserAction(username, 'block');
}

ezyadmin.activateUser = function(username) {
    ezyadmin.doUserAction(username, 'activate');
}

// ==================== delete a user ============
ezyadmin.onDeleteUserClick = function(username) {
    ezyadmin.selectedUsername = username;
    $('#delete-user-modal-body-content')
        .text(ezyadmin.messages.do_you_want_to_delete_user.replace('{0}', username));
    $('#delete-user-modal').modal('show');
}

// ==================== erase a user ============
ezyadmin.onEraseUserClick = function(username) {
    ezyadmin.selectedUsername = username;
    $('#erase-user-modal-body-content')
        .text(ezyadmin.messages.do_you_want_to_erase_user.replace('{0}', username));
    $('#erase-user-modal').modal('show');
}

ezyadmin.onPromptConfirmed = function(modalId) {
    ezyadmin.onPromptUserActionConfirmed(modalId);
}

ezyadmin.onPromptUserActionConfirmed = function(modalId) {
    if (modalId == 'erase-user-modal') {
        ezyadmin.doUserAction(ezyadmin.selectedUsername, 'erase');
    } else if (modalId == 'delete-user-modal') {
        ezyadmin.doUserAction(ezyadmin.selectedUsername, 'delete');
    }
}

ezyadmin.doUserAction = function(username, action) {
    var type = 'PUT';
    var url = '/api/v1/users/' + username + '/' + action;
    if (action == 'erase' || action == 'delete') {
        type = 'DELETE';
    }
    if (action == 'delete') {
        url = '/api/v1/users/' + username;
    }
    $.ajax({
        type: type,
        url: url,
        contentType: 'application/json'
    }).done(function () {
        $('#erase-user-modal').modal('hide');
        $('#delete-user-modal').modal('hide');
        if (ezyadmin.onAfterUserAction) {
            ezyadmin.onAfterUserAction(action);
        } else if (ezyadmin.fetchUserList) {
            ezyadmin.fetchUserList('current');
        } else if (action == 'erase' || action == 'delete') {
            var url;
            if (ezyadmin.currentParentURL
                && ezyadmin.currentParentURL != '/users'
            ) {
                url = ezyadmin.currentParentURL;
            } else {
                url = '/users/' + (ezyadmin.lang ? '?lang=' + ezyadmin.lang : '');
            }
            window.location = url;
        } 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.messages[action] || ezyadmin.toDisplayString(action)) +
                ' ' + username + ' ' + ezyadmin.messages.failed.toLowerCase(),
            errorBody
        );
    });
}
</script>
</body>
</html>
