{% extends "sysadmin/base.html" %}
{% load seahub_tags i18n %}
{% block cur_users %}tab-cur{% endblock %}

{% block left_panel %}{{block.super}}
<form action="{% url 'user_search' %}" method="get" class="side-search-form">
    <input type="text" name="email" class="input" value="" placeholder="{% trans "Search users..." %}" />
</form>
{% endblock %}

{% block right_panel %}
<div class="tabnav ovhd">
    <ul class="tabnav-tabs fleft">
        <li class="tabnav-tab tabnav-tab-cur"><a href="{% url 'sys_useradmin' %}">{% trans "Database" %}</a></li>
        {% if have_ldap %}
        <li class="tabnav-tab"><a href="{% url 'sys_useradmin_ldap' %}">{% trans "LDAP" %}</a></li>
        <li class="tabnav-tab"><a href="{% url 'sys_useradmin_ldap_imported' %}">{% trans "LDAP(imported)" %}</a></li>
        {% endif %}
        <li class="tabnav-tab"><a href="{% url 'sys_useradmin_admins' %}">{% trans "Admins" %}</a></li>
        {% if enable_user_plan %}
        <li class="tabnav-tab"><a href="{% url 'sys_useradmin' %}?filter=paid">Paid</a></li>
        {% endif %}
    </ul>
    <div class="fright">
        <button id="import-users-btn">{% trans "Import users" %}</button>
        <button id="add-user-btn">{% trans "Add user" %}</button>
        <button id="export-excel">{% trans "Export Excel" %}</button>
    </div>
</div>

<form id="add-user-form" action="" method="post" class="hide">{% csrf_token %}
    <h3>{% trans "Add user" %}</h3>
    <label for="id_email">{% trans "Email" %}</label><br />
    <input type="text" name="email" id="id_email" class="input" /><br />
    {% if is_pro %}
    <label>{% trans "Role"%}</label><span class="icon-question-sign" title="{% trans "You can also add a user as a guest, who will not be allowed to create libraries and groups." %}" style="color:#666; margin-left:3px;"></span>
    <select name="role" class="w100">
        <option value={{default_user}} selected="selected">{% trans "Default"%}</option>
        <option value={{guest_user}}>{% trans "Guest"%}</option>
    </select><br />
    {% endif %}
    <label for="id_password1">{% trans "Password" %}</label>
    <div class="passwd-wrapper">
        <input type="password" name="password1" id="id_password1" class="passwd input" />
        <span title="{% trans "Show" %}" class="icon-eye show-or-hide-password cspt"></span>
        <span title="{% trans "Generate a random password" %}" class="icon-magic generate-random-password cspt"></span>
    </div>
    <label for="id_password2">{% trans "Confirm Password" %}</label><br />
    <input type="password" name="password2" id="id_password2" class="input" /><br />
    <p class="error hide"></p>
    <button type="submit" class="submit">{% trans "Submit" %}</button>
</form>

<form id="upload-csv-form" class="hide" enctype="multipart/form-data" method="post" action="{% url 'batch_add_user' %}">{% csrf_token %}
    <h3>{% trans "Import users from a CSV file" %}</h3>
    <input type="file" name="file" />
    <p class="tip">{% trans "File format: user@mail.com,password"%}</p>
    <p class="error hide">{% trans "Please choose a CSV file" %}</p>
    <button type="submit" class="submit">{% trans "Submit" %}</button>
</form>

{% with is_admin_page=False%}
{% include "sysadmin/useradmin_table.html" %}
{% endwith %}
{% include "snippets/admin_paginator.html" %}

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

{% block extra_script %}
<script type="text/javascript">
$(function(){
    // check if server version is the latest one
    $.ajax({
        url: 'https://www.seafile.com/ajax/check_server_version/?v=' + e('{{seafile_version}}') + '&p=' + e('{{platform}}') + '&id=' + '{{server_id}}' + '&pro=' + '{{pro_server}}',
        dataType: 'jsonp',
        jsonpCallback: 'xx',
        crossDomain: true,
        success: function(data) {
            if (data['need_update']) {
                var tip = "{% trans "A new server version %(v)s is available." %}";
                tip = tip.replace('%(v)s', data['new_version']);
                $('#right-panel').prepend('<p class="strip-tip">' + tip + '</p>');
            }
        }
    });

    {% if is_pro %}
    // check if seafile license expired
    $.ajax({
        url: "{% url 'sys_check_license' %}",
        dataType: 'json',
        cache: false,
        success: function(data) {
            var tip;

            if (data['already_expired']) {
                tip = "Your license expired on %(date)s.";
            } else if (data['to_be_expired']) {
                tip = "Your license will expire on %(date)s.";
            }

            if (data['already_expired'] || data['to_be_expired']) {
                tip = tip.replace('%(date)s', data['expiration_date']);
                $('#right-panel').prepend('<p class="strip-tip">' + tip + '</p>');
            }
        }
    });
    {% endif %}
});

$('#add-user-btn').click(function() {
    $('#add-user-form').modal();
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
});
$('#add-user-form .show-or-hide-password').click(function() {
    var icon = $(this),
        passwd_input = $('input[name=password1], input[name=password2]', $('#add-user-form'));
    icon.toggleClass('icon-eye icon-eye-slash');
    if (icon.hasClass('icon-eye')) {
        icon.attr('title', "{% trans "Show" %}");
        passwd_input.prop('type', 'password');
    } else {
        icon.attr('title', "{% trans "Hide" %}");
        passwd_input.prop('type', 'text');
    }
});
$('#add-user-form .generate-random-password').click(function() {
    var form = $('#add-user-form');
    var random_password = '';
    var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789';
    for (var i = 0; i < 8; i++) {
        random_password += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    $('input[name=password1], input[name=password2]', form).prop('type', 'text').val(random_password);
    $('.show-or-hide-password', form)
    .attr('title', "{% trans "Hide" %}")
    .removeClass('icon-eye').addClass('icon-eye-slash');
});
$('#add-user-form').submit(function() {
    var form = $(this),
        form_id = $(this).attr('id'),
        email = $.trim(form.children('[name="email"]').val()),
        {% if is_pro %}
        role = $('select[name="role"]', form).val(),
        {% endif %}
        pwd1 = $.trim(form.find('[name="password1"]').val()),
        pwd2 = $.trim(form.children('[name="password2"]').val());

    if (!email) {
        apply_form_error(form_id, "{% trans "Email cannot be blank" %}");
        return false;
    }
    if (!pwd1) {
        apply_form_error(form_id, "{% trans "Password cannot be blank" %}");
        return false;
    } 
    if (!pwd2) {
        apply_form_error(form_id, "{% trans "Please enter the password again" %}");
        return false;
    } 
    if (pwd1 != pwd2) {
        apply_form_error(form_id, "{% trans "Passwords do not match" %}");
        return false;
    } 

    var submit_btn = $(this).find('[type="submit"]');
    disable(submit_btn);
    $.ajax({
        url: '{% url 'user_add' %}',
        type: 'POST',
        datatype: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        data: {
            'email': email,
            {% if is_pro %}
            'role': role,
            {% endif %}
            'password1': pwd1,
            'password2': pwd2
        },
        success: function(data) {
            if (data['success']) {
                location.reload(true);
            }   
        },  
        error: function(jqXHR, textStatus, errorThrown) {
            if (jqXHR.responseText) {
                apply_form_error(form_id, $.parseJSON(jqXHR.responseText).error);
            } else {
                apply_form_error(form_id, "{% trans "Failed. Please check the network." %}");
            }
            enable(submit_btn);
        }
    });
    return false;
});
$('#import-users-btn').click(function () {
    $('#upload-csv-form').modal();
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
});
$('#upload-csv-form').submit(function() {
    var form = $(this);
    if (!$('[name=file]', form).val()) {
        $('.error', form).removeClass('hide');
        return false;
    }
});
$("#export-excel").click(function() {
    location.href = "{% url 'sys_useradmin_export_excel' %}";
});
{% include "sysadmin/useradmin_js.html" %}
</script>
{% endblock %}
