{% extends "sysadmin/base.html" %}
{% load i18n avatar_tags seahub_tags 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 %}

<p class="path-bar">
    <a class="normal" href="{{ SITE_ROOT }}sys/useradmin/">Users</a>
    <span class="path-split">/</span>
    {{ email }}
</p>

<div id="tabs" class="tab-tabs">
    <div class="hd header-bar ovhd">
        <ul class="tab-tabs-nav fleft">
            <li class="tab"><a href="#profile" class="a">{% trans "Profile" %}</a></li>
            <li class="tab"><a href="#owned" class="a">{% trans "Owned Libs" %}</a></li>
            <li class="tab"><a href="#shared" class="a">{% trans "Shared Libs" %}</a></li>
            <li class="tab"><a href="#shared-links" class="a">{% trans "Shared Links" %}</a></li>
            <li class="tab"><a href="#user-admin-groups" class="a">{% trans "Groups" %}</a></li>
        </ul>
    </div>

    <div id="profile">
        <dl>
            <dt>{% trans "Avatar" %}</dt>
            <dd>{% avatar email 48 %}</dd>

            <dt>{% trans "Email" %}</dt>
            <dd>{{ email }}</dd>

            {% if org_name %}
            <dt>{% trans "Organization" %}</dt>
            <dd>{{ org_name }}</dd>
            {%  endif %}

            <dt>{% trans "Name" context "true name" %}</dt>
            <dd>
                <span id="nickname">
                    {% if profile and profile.nickname %}
                    {{ profile.nickname }}
                    {% else %}
                    --
                    {% endif %}
                </span>
                <span id="set-name" title="{% trans "Edit"%}" class="sf2-icon-edit op-icon"></span>
            </dd>

            <dt>{% trans "Login ID" %}</dt>
            <dd>
                <span id="loginid">
                    {% if profile and profile.login_id %}
                    {{ profile.login_id }}
                    {% else %}
                    --
                    {% endif %}
                </span>
                <span id="set-loginid" title="{% trans "Edit"%}" class="sf2-icon-edit op-icon"></span>
            </dd>

            <dt>{% trans "Contact Email" %}</dt>
            <dd>
                <span id="contact-email">
                    {% if profile and profile.contact_email %}
                    {{ profile.contact_email }}
                    {% else %}
                    --
                    {% endif %}
                </span>
                <span id="set-contact-email" title="{% trans "Edit"%}" class="sf2-icon-edit op-icon"></span>
            </dd>

            <dt>{% trans "Reference ID" %}</dt>
            <dd>
                <span id="reference-id">
                    {% if reference_id %}
                    {{ reference_id }}
                    {% else %}
                    --
                    {% endif %}
                </span>
                <span id="set-reference-id" title="{% trans "Edit" %}" class="sf2-icon-edit op-icon"></span>
            </dd>

            {% if d_profile and d_profile.telephone %}
            <dt>{% trans "Telephone" %}</dt>
            <dd>{{ d_profile.telephone }}</dd>
            {% endif %}

            <dt>{% trans "Space Used / Quota" %}</dt>
            <dd>
                {{ space_usage|seahub_filesizeformat }} /
                <span id="quota">
                    {% if space_quota >= 0 %}
                    {{ space_quota|seahub_filesizeformat }}
                    {% elif space_quota == -2 %}
                    --
                    {% else %}
                    <span class="error">{% trans "Error" %}</span>
                    {% endif %}
                </span>
                <span id="set-quota" title="{% trans "Edit Quota" %}" class="sf2-icon-edit op-icon"></span>
            </dd>

            {% if two_factor_auth_enabled %}
            <dt>{% trans "Two-Factor Authentication" %}</dt>
            <dd>
                {% if default_device %}
                <p class="txt-before-btn">{% trans "Status" %}: {% trans "enabled" %}</p>
                <button id="disable-two-factor-auth">{% trans "Disable Two-Factor Authentication" %}</button>
                {% else %}
                <button disabled="disabled" class="btn-disabled">{% trans "Disable Two-Factor Authentication" %}</button>
                {% endif %}
            </dd>
            {% endif %}

        </dl>

        <form id="set-name-form" method="post" action="" class="hide">{% csrf_token %}
            <h3>{% trans "Set user name" %}</h3>
            <input type="text" name="nickname" class="input" value="" /><br />
            <p class="error hide"></p>
            <input type="submit" value="{% trans "Submit" %}" class="submit" />
        </form>

        <form id="set-dept-form" method="post" action="" class="hide">{% csrf_token %}
            <h3>{% trans "Set user department" %}</h3>
            <input type="text" name="department" class="input" value="" /><br />
            <p class="error hide"></p>
            <input type="submit" value="{% trans "Submit" %}" class="submit" />
        </form>

        <form id="set-loginid-form" method="post" action="" class="hide">{% csrf_token %}
            <h3>{% trans "Set user Login ID" %}</h3>
            <input type="text" name="loginid" class="input" value="" /><br />
            <p class="error hide"></p>
            <input type="submit" value="{% trans "Submit" %}" class="submit" />
        </form>

        <form id="set-contact-email-form" method="post" action="" class="hide">{% csrf_token %}
            <h3>{% trans "Set user contact email" %}</h3>
            <input type="text" name="contact_email" class="input" value="" /><br />
            <p class="error hide"></p>
            <input type="submit" value="{% trans "Submit" %}" class="submit" />
        </form>

        <form id="set-reference-id-form" method="post" action="" class="hide">{% csrf_token %}
            <h3>{% trans "Set user Reference ID" %}</h3>
            <input type="text" name="reference_id" class="input" value="" /><br />
            <p class="error hide"></p>
            <input type="submit" value="{% trans "Submit" %}" class="submit" />
        </form>

        <form id="set-quota-form" method="post" class="hide">{% csrf_token %}
            <h3>{% trans "Set quota" %}</h3>
            <input type="text" name="space_quota" class="input" /> MB
            <p class="tip">
            <span>{% trans "An integer that is greater than or equal to 0." %}</span><br />
            <span>{% trans "Tip: 0 means default limit" %}</span>
            </p>
            <p class="error hide"></p>
            <input type="submit" value="{% trans "Submit" %}" class="submit" />
        </form>
    </div>

    <div id="owned" class="hide">
        {% if owned_repos %}
        <table class="repo-list">
            <tr>
                <th width="4%"><!--icon--></th>
                <th width="35%">{% trans "Name" %}</th>
                <th width="16%">{% trans "Size"%}</th>
                <th width="25%">{% trans "Last Update"%}</th>
                <th width="20%">{% trans "Operations" %}</th>
            </tr>

            {% for repo in owned_repos %}
            <tr>
                {% if repo.encrypted %}
                <td><img src="{{MEDIA_URL}}img/lib/48/lib-encrypted.png" width="24" title="{% trans "Encrypted"%}" alt="{% trans "library icon" %}" /></td>
                {% else %}
                <td><img src="{{MEDIA_URL}}img/lib/48/lib.png" width="24" title="{% trans "Read-Write" %}" alt="{% trans "library icon" %}" /></td>
                {% endif %}

                {% if not repo.name %}
                    <td>Broken ({{repo.id}})</td>
                {% else %}
                    {% if repo.encrypted %}
                        <td>{{ repo.name }}</td>
                    {% elif enable_sys_admin_view_repo %}
                        <td><a href="{{ SITE_ROOT }}sysadmin/#libs/{{ repo.id }}/">{{ repo.name }}</a></td>
                    {% else %}
                        <td>{{ repo.name }}</td>
                    {% endif %}
                {% endif %}

                <td>{{ repo.size|filesizeformat }}</td>
                <td>{{ repo.last_modify|translate_seahub_time }}</td>
                <td data-id="{{ repo.props.id }}" data-name="{{repo.name}}">
                    <div>
                        <a href="#" class="repo-delete-btn op vh">{% trans "Delete" %}</a>
                        <a href="#" class="repo-transfer-btn op vh">{% trans "Transfer" %}</a>
                    </div>
                </td>
            </tr>
            {% endfor %}
        </table>
        {% else %}
        <div class="empty-tips">
            <h2 class="alc">{% trans "This user has not created any libraries" %}</h2>
        </div>
        {% endif %}
    </div>

    <div id="shared" class="hide">
        {% if in_repos %}
        <table>
            <tr>
                <th width="4%"><!--icon--></th>
                <th width="30%">{% trans "Name" %}</th>
                <th width="26%">{% trans "Share From" %}</th>
                <th width="15%">{% trans "Size"%}</th>
                <th width="25%">{% trans "Last Update"%}</th>
            </tr>

            {% for repo in in_repos %}
            <tr>
                {% if repo.encrypted %}
                <td><img src="{{MEDIA_URL}}img/lib/48/lib-encrypted.png" width="24" title="{% trans "Encrypted"%}" alt="{% trans "library icon" %}" /></td>
                {% elif repo.permission == 'r' %}
                <td><img src="{{MEDIA_URL}}img/lib/48/lib-readonly.png" width="24" title="{% trans "Read-Only"%}" alt="{% trans "library icon" %}" /></td>
                {% else %}
                <td><img src="{{MEDIA_URL}}img/lib/48/lib.png" width="24" title="{% trans "Read-Write" %}" alt="{% trans "library icon" %}" /></td>
                {% endif %}
                {% if enable_sys_admin_view_repo %}
                <td><a href="{{ SITE_ROOT }}sysadmin/#libs/{{ repo.id }}/">{{ repo.name }}</a></td>
                {% else %}
                <td>{{ repo.name }}</td>
                {% endif %}
                <td>{{ repo.props.user }}</td>
                <td>{{ repo.size|filesizeformat }}</td>
                <td>{{ repo.last_modify|translate_seahub_time }}</td>
            </tr>
            {% endfor %}
        </table>
        {% else %}
        <div class="empty-tips">
            <h2 class="alc">{% trans "This user has no shared libraries" %}</h2>
        </div>
        {% endif %}
    </div>

    <div id="shared-links" class="hide">
        {% if user_shared_links%}
        <table class="sharelink-list">
            <tr>
                <th width="5%"><!--icon--></th>
                <th width="30%">{% trans "Name"%}</th>
                <th width="20%">{% trans "Size"%}</th>
                <th width="20%">{% trans "Type"%}</th>
                <th width="10%">{% trans "Visits"%}</th>
                <th width="15%">{% trans "Operations"%}</th>
            </tr>
            {% for link in user_shared_links %}
            <tr>
                {% if link.is_download %}
                    {% if link.is_file_share_link %}
                    <td class="alc"><img src="{{ MEDIA_URL }}img/file/{{ link.filename|file_icon_filter }}" alt="{% trans "File"%}" /></td>
                    <td>{{ link.filename }}</td>
                    <td>{{ link.file_size|filesizeformat}}</td>
                    {% else %}
                    <td class="alc"><img src="{{ MEDIA_URL }}img/folder-24.png" alt="{% trans "Directory icon"%}" /></td>
                    <td>{{ link.filename }}</td>
                    <td>{{ link.dir_size|filesizeformat}}</td>
                    {% endif %}
                    <td>{% trans "Download" %}</td>
                    <td>{{ link.view_cnt }}</td>
                    <td>
                        <a class="op vh rm-link" href="#" data-url="{% url 'sys_publink_remove' %}" data-token="{{ link.token }}">{% trans "Remove"%}</a>
                    </td>
                {% else %}
                    <td class="alc"><img src="{{ MEDIA_URL }}img/folder-24.png" alt="{% trans "Directory icon"%}" /></td>
                    <td>{{ link.dir_name }}</td>
                    <td>--</td>
                    <td>{% trans "Upload" %}</td>
                    <td>{{ link.view_cnt }}</td>
                    <td>
                        <a class="op vh rm-link" href="#" data-url="{% url 'sys_upload_link_remove' %}" data-token="{{ link.token }}">{% trans "Remove"%}</a>
                    </td>
                {% endif %}
            </tr>
            {% endfor %}
        </table>
        {% else %}
        <div class="empty-tips">
            <h2 class="alc">{% trans "This user has not created any shared links" %}</h2>
        </div>
        {% endif %}
    </div>

    <div id="user-admin-groups" class="hide">
        {% if personal_groups %}
        <table>
            <tr>
                <th width="30%">{% trans "Name" %}</th>
                <th width="30%">{% trans "Role" %}</th>
                <th width="25%">{% trans "Create At" %}</th>
                <th width="15%">{% trans "Operations" %}</th>
            </tr>
            {% for group in personal_groups %}
                <tr>
                    <td><a href="{{ SITE_ROOT }}sysadmin/#groups/{{ group.id }}/libs/">{{ group.group_name }}</a></td>
                    <td>{{ group.role }}</td>
                    <td>{{ group.timestamp|tsstr_sec }}</td>
                    <td><a href="#" data-url="{% url 'group_remove' group.id %}" data-target="{{ group.group_name }}" class="rm-grp op vh">{% trans "Delete" %}</a></td>
                </tr>
            {% endfor %}
        </table>
        {% else %}
        <div class="empty-tips">
            <h2 class="alc">{% trans "This user has not created or joined any groups" %}</h2>
        </div>
        {% endif %}
    </div>
</div>

{% include "sysadmin/repo_transfer_form.html" %}
{% endblock %}


{% block extra_script %}
<script type="text/javascript" src="{% static "scripts/lib/jquery-ui.min.js" %}"></script> {# for tabs #}
<script type="text/javascript" src="{% static "scripts/lib/select2-3.5.2.js" %}"></script>
<script type="text/javascript">
$('#tabs').tabs({cookie:{expires:1}});

{% include "sysadmin/repoadmin_js.html" %}

$('.rm-link').on('click', function() {
    var _this = $(this);
    $.ajax({
        url: _this.attr('data-url'),
        type: 'POST',
        data: {'t': _this.attr('data-token')},
        cache: false,
        dataType: 'json',
        beforeSend: prepareCSRFToken,
        success: function() {
            _this.closest('tr').remove();
        },
        error: ajaxErrorHandler
    });
    return false;
});
$('#set-name').on('click', function() {
    $("#set-name-form").modal({appendTo: "#main"});
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
});
$('#set-loginid').on('click', function () {
    $("#set-loginid-form").modal({appendTo:"#main"});
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
})
$('#set-contact-email').on('click', function() {
    $("#set-contact-email-form").modal({appendTo: "#main"});
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
});
$('#set-reference-id').on('click', function () {
    $("#set-reference-id-form").modal({appendTo:"#main"});
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
})
$('#set-dept').on('click', function() {
    $("#set-dept-form").modal({appendTo: "#main"});
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
});
$('#set-quota').on('click', function() {
    $("#set-quota-form").modal({appendTo: "#main"});
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
});

$("#disable-two-factor-auth").on('click', function(){
    $.ajax({
        url: '{% url 'two-factor-auth-view' email %}',
        type: 'DELETE',
        cache: false,
        beforeSend: prepareCSRFToken,
        success:function(data){
            location.reload(true);
        },
        error: ajaxErrorHandler
    });
});

$('#set-name-form').on('submit', function() {
    var nickname = $.trim($('[name="nickname"]', $(this)).val());
    var $name = $('#nickname');
    var $error = $('.error', $(this));
    if (nickname.indexOf('/') != -1) {
        $error.html("{% trans "Name should not include '/'." %}").show();
        return false;
    }

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

    $.ajax({
        url: '{% url 'api-v2.1-admin-user' email %}',
        type: 'PUT',
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        data: {'name': nickname},
        success: function(data) {
            if (nickname == '') {
                $name.html('--');
            } else {
                $name.html(HTMLescape(data['name']));
            }
            $.modal.close();
        },
        error: function(xhr, textStatus, errorThrown) {
            var err_msg = prepareAjaxErrorMsg(xhr);
            $error.html(err_msg).show();
            enable($submitBtn);
        }
    });

    return false;
});

$('#set-loginid-form').on('submit', function() {
    var loginid = $.trim($('[name="loginid"]', $(this)).val());
    var $loginid = $('#loginid');
    var $error = $('.error', $(this));
    var $submitBtn = $('[type="submit"]', $(this));

    disable($submitBtn);

    $.ajax({
        url: '{% url 'api-v2.1-admin-user' email %}',
        type: 'PUT',
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        data: {'login_id': loginid},
        success: function(data) {
            if (loginid == '') {
                $loginid.html('--');
            } else {
                $loginid.html(HTMLescape(data['login_id']));
            }
            $.modal.close();
        },
        error: function(xhr, textStatus, errorThrown) {
            var err_msg = prepareAjaxErrorMsg(xhr);
            $error.html(err_msg).show();
            enable($submitBtn);
        }
    });

    return false;
});

$('#set-contact-email-form').on('submit', function() {
    var $form = $(this);
    var contact_email = $.trim($('[name="contact_email"]', $form).val());
    var $contactEmail = $('#contact-email');
    var $error = $('.error', $form);

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

    $.ajax({
        url: '{% url 'api-v2.1-admin-user' email %}',
        type: 'PUT',
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        data: {'contact_email': contact_email},
        success: function(data) {
            if (data['contact_email'] == ''){
                $contactEmail.html('--');
            } else {
                $contactEmail.html(HTMLescape(data['contact_email']));
            }
            $.modal.close();
        },
        error: function(xhr, textStatus, errorThrown) {
            var err_msg = prepareAjaxErrorMsg(xhr);
            $error.html(err_msg).show();
            enable($submitBtn);
        }
    });

    return false;
});

$('#set-reference-id-form').on('submit', function() {
    var reference_id = $.trim($('[name="reference_id"]', $(this)).val());
    var $referenceID = $('#reference-id');
    var $error = $('.error', $(this));
    var $submitBtn = $('[type="submit"]', $(this));
    disable($submitBtn);

    $.ajax({
        url: '{% url 'api-v2.1-admin-user' email %}',
        type: 'PUT',
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        data: {'reference_id': reference_id},
        success: function(data) {
            if (reference_id == '') {
                $referenceID.html('--');
            } else {
                $referenceID.html(HTMLescape(data['reference_id']));
            }
            $.modal.close();
        },
        error: function(xhr, textStatus, errorThrown) {
            var err_msg = prepareAjaxErrorMsg(xhr);
            $error.html(err_msg).show();
            enable($submitBtn);
        }
    });

    return false;
});

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

    if (!space_quota) {
        apply_form_error(form_id, "{% trans "It is required." %}");
        return false;
    }

    if (!(quota_int == space_quota && quota_int >= 0)) {
        apply_form_error(form_id, "{% trans "Invalid quota." %}");
        return false;
    }

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

    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;
    };
    $.ajax({
        url: '{% url 'api-v2.1-admin-user' email %}',
        type: 'PUT',
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        data: {'quota_total': space_quota},
        success: function(data) {
            $('#quota').html(getQuotaShown(data['quota_total']));
            $.modal.close();
        },
        error: function(xhr, textStatus, errorThrown) {
            var err_msg = prepareAjaxErrorMsg(xhr);
            apply_form_error(form_id, err_msg);
            enable($submitBtn);
        }
    });
    return false;
});

addConfirmTo($('.rm-grp'), {
    'title': "{% trans "Delete Group" %}",
    'con': "{% trans "Are you sure you want to delete %s ?" %}",
    'post': true
});
</script>
{% endblock %}
