{% load i18n%}
addConfirmTo($('.remove-user-btn'), {
    'title':"{% trans "Delete User" %}",
    'con':"{% trans "Are you sure you want to delete %s ?" %}",
    'post': true // post request
});
addConfirmTo($('.reset-user-btn'), {
    'title':"{% trans "Password Reset" %}",
    'con':"{% trans "Are you sure you want to reset the password of %s ?" %}",
    'post': true // post request
});
addConfirmTo($('.revoke-admin-btn'), {
    'title':"{% trans "Revoke Admin" %}",
    'con':"{% trans "Are you sure you want to revoke the admin permission of %s ?" %}",
    'post': true // post request
});
addConfirmTo($('.unset-trial'), {
    'title': "Remove Trial",
    'con':"Are you sure you want to remove trial for %s ?",
    'post': true // post request
});

$('.user-status-edit-icon, .user-role-edit-icon, .user-institution-edit-icon, .admin-role-edit-icon').on('click', function() {
    $(this).parent().addClass('hide');
    $(this).parent().next().removeClass('hide'); // show 'select'
});
$('.user-status-select, .user-role-select, .user-institution-select').on('change', function() {
    var select = $(this),
        select_val = select.val(),
        ajax_type = 'POST',
        uid = select.parents('tr').attr('data-userid'),
        $select_prev = $(this).prev('.user-status, .user-role, .user-institution'), // .user-status, .user-role, .user-institution
        url, data;

    if (select.hasClass('user-status-select')) {
        url = "{{ SITE_ROOT }}useradmin/toggle_status/" + uid + "/";
        data = {'s': select_val};
    } else if (select.hasClass('user-institution-select')){
        url = "{{ SITE_ROOT }}api2/accounts/" + uid + "/";
        data = {'institution': select_val};
        ajax_type = 'PUT';
    } else {
        url = "{{ SITE_ROOT }}useradmin/toggle_role/" + uid + "/";
        data = {'r': select_val};
    }

    if (select.hasClass('user-status-select') && select_val == 1) {
        // show activating popup
        $('#activate-msg').modal();
        $('#simplemodal-container').css({'height':'auto'});
    }
    $.ajax({
        url: url,
        type: ajax_type,
        dataType: 'json',
        data: data,
        cache: false,
        beforeSend: prepareCSRFToken,
        success: function(data) {
            if (data['email_sent']) {
                feedback("{% trans "Edit succeeded, an email has been sent." %}", 'success');
            } else if (data['email_sent'] === false) {
                feedback("{% trans "Edit succeeded, but failed to send email, please check your email configuration." %}", 'success');
            } else {
                feedback("{% trans "Edit succeeded" %}", 'success');
            }
            $('.user-status-cur-value, .user-role-cur-value, .user-institution-cur-value', $select_prev).html(select.children('option[value="' +select.val() + '"]').text());
            select.addClass('hide');
            $select_prev.removeClass('hide');
            $.modal.close();
        },
        error: function() {
            feedback("{% trans "Edit failed." %}", 'error');
            select.addClass('hide');
            $select_prev.removeClass('hide');
            $.modal.close();
        }
    });
});

// for 'select'
var $opForAll = $('.js-op-for-all');
var $opForSelected = $('.js-op-for-selected');
$('th [type="checkbox"]').on('click', function() {
    var all_checked = $(this).prop('checked');
    if (all_checked) {
        $('td [type="checkbox"]').prop('checked', true);
        $opForAll.hide();
        $opForSelected.show();
    } else {
        $('td [type="checkbox"]').prop('checked', false);
        $opForAll.show();
        $opForSelected.hide();
    }
});

$('td [type="checkbox"]').on('click', function() {
    if ($('td [type="checkbox"]:checked').length) {
        $opForAll.hide();
        $opForSelected.show();
    } else {
        $opForAll.show();
        $opForSelected.hide();
    }

    if ($('td [type="checkbox"]:checked').length == $('td [type="checkbox"]').length) {
        $('th [type="checkbox"]').prop('checked', true);
    } else {
        $('th [type="checkbox"]').prop('checked', false);
    }
});

$('#set-quota-btn').on('click', function() {
    $('#set-quota-form').data({'batch': true}).modal();
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
});

{% if show_institution %}
$('#set-institution-btn').on('click', function() {
    $('#batch-set-institution-form').modal({focus: false, minWidth: 280});
    $('#simplemodal-container').css({'height':'auto'});
});
$("#batch-set-institution-form").on('submit', function() {
    var $form = $(this);
    var $error = $('.error', $form);
    var $submit = $('[type="submit"]', $form);

    var institution = $('[name="institution"]', $form).val();
    var emails = [];
    $('td [type="checkbox"]:checked').closest('tr').each(function(index, item) {
        emails.push($(item).attr('data-userid'));
    });

    disable($submit);
    $.ajax({
        url: "{% url 'api-v2.1-admin-users-batch' %}",
        type: "POST",
        dataType: 'json',
        cache: false,
        data: {
            'operation': 'set-institution',
            'email': emails,
            'institution': institution
        },
        traditional: true,
        beforeSend: prepareCSRFToken,
        success: function(data) {
            if (data.success.length) {
                var emails = [];
                $(data.success).each(function(index, item) {
                    var $tr = $('tr[data-userid="' + item.email + '"]');
                    $('.user-institution-cur-value', $tr).html(HTMLescape(item.institution));
                    emails.push(item.email);
                });
                var msg = "{% trans "Successfully set institution for {users}." %}".replace('{users}', HTMLescape(emails.join(', ')));
                feedback(msg, 'success');
            }
            if (data.failed.length) {
                var err_msg = '';
                $(data.failed).each(function(index, item) {
                    err_msg += HTMLescape(item.email) + ': ' + item.error_msg + '<br />';
                });
                setTimeout(function() { feedback(err_msg, 'error'); }, 1500);
            }
            $.modal.close();
        },
        error: function(xhr, textStatus, errorThrown) {
            var error_msg = prepareAjaxErrorMsg(xhr);
            $error.html(error_msg).show();
            enable($submit);
        }
    });

    return false;
});
{% endif %}

$('#delete-users-btn').on('click', function() {
    var title = "{% trans "Delete User" %}";
    var content = "{% trans "Are you sure you want to delete the selected user(s) ?" %}";
    var yesCallback = function() {
        var emails = [];
        $('td [type="checkbox"]:checked').closest('tr').each(function(index, item) {
            var email = $(item).attr('data-userid');
            if (email != "{{request.user.username|escapejs}}") {
                emails.push(email);
            }
        });
        $.ajax({
            url: '{% url "api-v2.1-admin-users-batch" %}',
            type: 'POST',
            cache: false,
            data: {
                'operation': 'delete-user',
                'email': emails
            },
            traditional: true,
            dataType: 'json',
            beforeSend: prepareCSRFToken,
            success: function(data) {
                if (data.success.length) {
                    var emails = [];
                    $(data.success).each(function(index, item) {
                        $('tr[data-userid="' + item.email + '"]').remove();
                        emails.push(item.email);
                    });
                    var msg = "{% trans "Successfully deleted {users}." %}".replace('{users}', HTMLescape(emails.join(', ')));
                    feedback(msg, 'success');
                }

                // all selected items are deleted
                if ($('td [type="checkbox"]:checked').length == 0) {
                    $opForAll.show();
                    $opForSelected.hide();
                }

                if (data.failed.length) {
                    var err_msg = '';
                    $(data.failed).each(function(index, item) {
                        err_msg += HTMLescape(item.email) + ': ' + item.error_msg + '<br />';
                    });
                    setTimeout(function() { feedback(err_msg, 'error'); }, 1500);
                }
            },
            error: ajaxErrorHandler,
            complete: function() {
                $.modal.close();
            }
        });
    };
    showConfirm(title, content, yesCallback);
});

// edit quota
$('.quota-edit-icon').on('click', function() {
    var email = $(this).closest('tr').attr('data-userid');
    var $spaceQuota = $(this).prev('.user-space-quota');
    $('#set-quota-form').data({'batch': false, 'email': email, '$spaceQuota': $spaceQuota}).modal();
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
});

$('#set-quota-form').on('submit', function() {
    var space_quota = $.trim($('[name="space_quota"]', $(this)).val());
    var quota_int = parseInt(space_quota);
    var $error = $('.error', $(this));

    if (!space_quota) {
        $error.html("{% trans "It is required." %}").show();
        return false;
    }

    if (!(quota_int == space_quota && quota_int >= 0)) {
        $error.html("{% trans "Invalid quota." %}").show();
        return false;
    }

    var $submitBtn = $('[type="submit"]', $(this));
    disable($submitBtn);

    var batch = $(this).data('batch');
    var options = {};
    var getQuotaShown = function(quota) {
        var quota_shown;
        if (quota >= 0) {
            quota_shown = quotaSizeFormat(parseInt(quota), 1);
        } else if (quota == -2) {
            quota_shown = '--';
        } else {
            quota_shown = '<span class="error">{% trans "Error" %}</span>';
        }
        return quota_shown;
    };

    if (batch) {
        var emails = [];
        $('td [type="checkbox"]:checked').closest('tr').each(function(index, item) {
            emails.push($(item).attr('data-userid'));
        });
        options = {
            url: '{% url "api-v2.1-admin-users-batch" %}',
            type: 'POST',
            data: {
                'operation': 'set-quota',
                'email': emails,
                'quota_total': space_quota
            },
            traditional: true,
            success: function(data) {
                if (data.success.length) {
                    var emails = [];
                    $(data.success).each(function(index, item) {
                        var $tr = $('tr[data-userid="' + item.email + '"]');
                        var $quota = $('.user-space-quota', $tr);
                        $quota.html(getQuotaShown(item.quota_total));
                        emails.push(item.email);
                    });
                    var msg = "{% trans "Successfully set quota for {users}." %}".replace('{users}', HTMLescape(emails.join(', ')));
                    feedback(msg, 'success');
                }
                if (data.failed.length) {
                    var err_msg = '';
                    $(data.failed).each(function(index, item) {
                        err_msg += HTMLescape(item.email) + ': ' + item.error_msg + '<br />';
                    });
                    setTimeout(function() { feedback(err_msg, 'error'); }, 1500);
                }
                $.modal.close();
            }
        };
    } else {
        var email = $(this).data('email');
        var $spaceQuota = $(this).data('$spaceQuota');
        options = {
            url: '{{ SITE_ROOT }}api2/accounts/' + encodeURIComponent(email) + '/',
            type: 'PUT',
            data: {'storage': space_quota},
            success: function(data) {
                $spaceQuota.html(getQuotaShown(data.total));
                var msg = "{% trans "Successfully set quota for {user}." %}".replace('{user}', HTMLescape(data.email));
                feedback(msg, 'success');
                $.modal.close();
            }
        };
    }

    $.ajax($.extend({
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        error: function(xhr, textStatus, errorThrown) {
            var err_msg = prepareAjaxErrorMsg(xhr);
            $error.html(err_msg).show();
            enable($submitBtn);
        }
    }, options));

    return false;
});

// select shows, but the user doesn't select a value, or doesn't change the permission, click other place to hide the select
$(document).on('click', function(e) {
    var target = e.target || event.srcElement;
    // target can't be edit-icon
    if (!$('.user-status-edit-icon, .user-status-select').is(target)) {
        $('.user-status').removeClass('hide');
        $('.user-status-select').addClass('hide');
    }
    if (!$('.user-role-edit-icon, .user-role-select').is(target)) {
        $('.user-role').removeClass('hide');
        $('.user-role-select').addClass('hide');
    }
    if (!$('.user-institution-edit-icon, .user-institution-select').is(target)) {
        $('.user-institution').removeClass('hide');
        $('.user-institution-select').addClass('hide');
    }
    if (!$('.admin-role-edit-icon, .admin-role-select').is(target)) {
        $('.admin-role').removeClass('hide');
        $('.admin-role-select').addClass('hide');
    }
});
