{% extends "sysadmin/sys_inst_info_base.html" %}
{% load i18n seahub_tags %}
{% load staticfiles %}

{% block extra_style %}
<link rel="stylesheet" type="text/css" href="{% static "css/select2-3.5.2.css" %}" />
<link rel="stylesheet" type="text/css" href="{% static "css/select2.custom.css" %}" />
{% endblock %}

{% block right_panel %}
<div class="tabnav">
    <ul class="tabnav-tabs">
        <li class="tabnav-tab tabnav-tab-cur"><a href="{% url 'sys_inst_info_users' inst.pk %}">{% trans "Members" %}</a></li>
        <li class="tabnav-tab"><a href="{% url 'sys_inst_info_admins' inst.pk %}">{% trans "Admins" %}</a></li>
    </ul>
    <div class="js-op-for-all fright">
        <button id="add-member-btn">{% trans "Add Members" %}</button>
    </div>
</div>

<form id="add-member-form" action="" method="" class="hide">
    <h3>{% trans "Add Members" %}</h3>
    <label>{% trans "Email" %}</label><br />
    <input type="hidden" name="emails" /><br />
    <p class="error hide"></p>
    <button type="submit" class="submit">{% trans "Submit" %}</button>
</form>
{% if users %}
<table>
    <tr>
        <th width="25%">{% trans "Email" %}</th>
        <th width="10%">{% trans "Status" %}</th>
        <th width="20%">{% trans "Space Used" %}</th>
        <th width="25%">{% trans "Create At / Last Login" %}</th>
        <th width="20%">{% trans "Operations" %}</th>
    </tr>

    {% for user in users %}
    <tr data-userid="{{user.email}}">
        <td><a href="{% url 'user_info' user.email %}">{{ user.email }}</a></td>
        <td>
            <div class="user-status">
              {% if user.is_active %}
                <span class="user-status-cur-value">{% trans "Active" %}</span>
              {% else %}
                <span class="user-status-cur-value">{% trans "Inactive" %}</span>
              {% endif %}
            </div>
        </td>
        <td style="font-size:11px;">
            {{ user.space_usage|seahub_filesizeformat }} {% if user.space_quota > 0 %} / {{ user.space_quota|seahub_filesizeformat }} {% endif %}
        </td>
        <td style="font-size:11px;">
            {{ user.ctime|tsstr_sec }} / {% if user.last_login %}{{user.last_login|translate_seahub_time}} {% else %} -- {% endif %}
        </td>
        <td>
          <a href="#" class="js-toggle-admin op vh" data-url="{% url 'sys_inst_toggle_admin' inst.pk user.email %}" data-target="{{ user.email }}">{% if user.inst_admin %}{% trans "Revoke Admin" %}{% else %}{% trans "Set Admin" %}{% endif %}</a>
        </td>
    </tr>
    {% endfor %}
</table>
{% include "snippets/admin_paginator.html" %}
{% else %}
<p>{% trans "Empty" %}</p>
{% endif %}

<div id="activate-msg" class="hide">
    <p>{% trans "Activating..., please wait" %}</p>
</div>

{% endblock %}

{% block extra_script %}{{ block.super }}
<script type="text/javascript" src= "{% static "scripts/lib/select2-3.5.2.js" %}"></script>

<script type="text/javascript">
addConfirmTo($('.js-toggle-admin'), {
    'title': "Toggle Admin",
    'con': "Sure ?",
    'post': true
});

$('.user-status-edit-icon').on('click', function() {
    $(this).parent().addClass('hide');
    $(this).parent().next().removeClass('hide'); // show 'select'
});
$('.user-status-select').on('change', function() {
    var select = $(this),
        select_val = select.val(),
        uid = select.parents('tr').attr('data-userid'),
        url = "{{ SITE_ROOT }}useradmin/toggle_status/" + uid + "/?s=" + select_val;

    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        cache: false,
        beforeSend: function() {
            if (select_val == 1) {
                // show activating popup
                $('#activate-msg').modal();
                $('#simplemodal-container').css({'height':'auto'});
            }
        },
        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');
            }
            select.prev().children('span').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();
        }
    });
});
$(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');
    }
});

// add members
$('#add-member-btn').on('click', function(){
    var $form = $('#add-member-form');
    $form.modal({focus: false});
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});

    $('[name="emails"]', $form).select2($.extend({
        width: '280px',
        placeholder: "{% trans "Search user or enter email and press Enter" %}",
        formatInputTooShort: "{% trans "Please enter 1 or more character" %}",
        formatNoMatches: "{% trans "No matches" %}",
        formatSearching: "{% trans "Searching..." %}",
        formatAjaxError: "{% trans "Loading failed" %}"
    }, userInputOPtionsForSelect2('{% url 'search-user' %}')));
});
$('#add-member-form').on('submit', function(){
    var $form = $(this);
    var $error = $('.error', $form);
    var $submit = $('[type="submit"]', $form);
    var emails = $('[name="emails"]', $form).select2('val');

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

    disable($submit);
    $.ajax({
        url: "{% url 'sys_inst_add_user' inst.id %}",
        type: 'POST',
        dataType: 'json',
        data: {
            'emails': emails.join(',')
        },
        beforeSend: prepareCSRFToken,
        success: function(data) {
            location.reload(true);
        },
        error: function(xhr, textStatus, errorThrown) {
            var error_msg = prepareAjaxErrorMsg(xhr);
            $error.html(error_msg).show();
            enable($submit);
        }
    });
    return false;
});
</script>
{% endblock %}
