{% extends "myhome_base.html" %}

{% load i18n avatar_tags seahub_tags staticfiles %}

{% block sub_title %}{{repo.name}} - {% endblock %}

{% 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 left_panel %}
<div class="side-textnav">
    <h3 class="hd"><span class="op-target">{{ repo.name }}</span> {% trans "Settings" %}</h3>
    <ul class="side-textnav-tabs">
        <li class="tab"><a href="{% url 'repo_basic_info' repo.id %}">{% trans "Basic Info" %}</a></li>
        <li class="tab"><a href="{% url 'repo_transfer_owner' repo.id %}">{% trans "Transfer Ownership" %}</a></li>
        {% if repo.encrypted and repo.enc_version == 2 %}
        <li class="tab"><a href="{% url 'repo_change_password' repo.id %}">{% trans "Change Password" %}</a></li>
        {% endif %}
        {% if not repo.encrypted %}
        <li class="tab"><a href="{% url 'repo_shared_link' repo.id %}">{% trans "Shared Links" %}</a></li>
        {% endif %}
        <li class="tab"><a href="{% url 'repo_share_manage' repo.id %}">{% trans "Sharing Permission" %}</a></li>
        <li class="tab tab-cur"><a href="{% url 'repo_folder_perm' repo.id %}">{% trans "Folder Permission" %}</a></li>
    </ul>
</div>
{% endblock %}

{% block right_panel %}
<div class="lib-setting">
    <div id="tabs" class="tab-tabs">
        <div class="hd ovhd">
            <ul class="tab-tabs-nav fleft">
                <li class="tab"><a href="#user-tab" class="a" id="user-tab">{% trans "User Permission" %}</a></li>
                <li class="tab"><a href="#group-tab" class="a" id="group-tab">{% trans "Group permission" %}</a></li>
            </ul>
            <div class="fright">
                <button id="folder-perm-add-btn"><img src="{{ MEDIA_URL }}img/add.png" alt="" class="add vam" /><span class="vam">{% trans "Add Permission" %}</span></button>
            </div>
        </div>

        <div id="user-tab">
            <table>
                <tr>
                    <th width="35%">{% trans "User" %}</th>
                    <th width="30%">{% trans "Folder" %}</th>
                    <th width="25%">{% trans "Permission" %}</th>
                    <th width="10%"></th>
                </tr>
                <tr class="user-perm-add-tr hide">
                    <td><input id="perm-add-user" type="hidden" class="w100" /></td>
                    <td>
                        <input class="user-perm-add-folder-name" placeholder="{% trans "Select a folder"%}" type="text" /><img src="{{ MEDIA_URL }}img/add.png" alt="" title="{% trans "Select a folder" %}" class="perm-add-select-folder add vam" />
                        <input class="user-perm-add-folder-path" type="hidden" />
                    </td>
                    <td>
                        <select name="permission" class="user-perm-add-perm w100">
                            <option value="rw" selected="selected">{% trans "Read-Write"%}</option>
                            <option value="r">{% trans "Read-Only"%}</option>
                        </select>
                    </td>
                    <td>
                        <button class="perm-add-submit">{% trans "Submit" %}</button>
                    </td>
                </tr>
                {% if user_folder_perms %}
                {% for perm in user_folder_perms %}
                <tr class="perm-item" data-user="{{ perm.user }}" data-path="{{ perm.path }}" data-perm="{{ perm.permission }}">
                    <td><a href="{% url 'user_profile' perm.user %}">{{ perm.user }}</a></td>
                    <td><span><a href="{% url 'view_common_lib_dir' repo.id perm.path|urlencode|strip_slash %}">{{ perm.folder_name }}</a></span></td>
                    <td>
                        <div class="perm-change">
                          {% if perm.permission == 'rw' %}
                            <span class="perm-cur-value">{% trans "Read-Write" %}</span>
                          {% else %}
                            <span class="perm-cur-value">{% trans "Read-Only" %}</span>
                          {% endif %}
                            <img src="{{MEDIA_URL}}img/edit_12.png" alt="{% trans "Edit"%}" title="{% trans "Edit"%}" class="perm-edit-icon cspt vh" />
                        </div>
                        <select class="perm-toggle-select hide">
                            <option value="rw" {%if perm.permission == 'rw' %}selected="selected"{% endif %}>{% trans "Read-Write" %}</option>
                            <option value="r" {%if not perm.permission == 'rw' %}selected="selected"{% endif %}>{% trans "Read-Only"%}</option>
                        </select>
                    </td>
                    <td>
                        <img src="{{MEDIA_URL}}img/rm.png" class="perm-delete-btn op-icon vh" title="{% trans "Delete" %}" />
                    </td>
                </tr>
                {% endfor %}
                {% endif %}
            </table>
        </div>

        <div id="group-tab" class="hide">
            <table>
                <tr>
                    <th width="35%">{% trans "Group" %}</th>
                    <th width="30%">{% trans "Folder" %}</th>
                    <th width="25%">{% trans "Permission" %}</th>
                    <th width="10%"></th>
                </tr>
                <tr class="group-perm-add-tr hide">
                    <td>
                        <input id="perm-add-grp-name" placeholder="{% trans "Group"%}" type="text" />
                        <input id="perm-add-grp-id" type="hidden" />
                    </td>
                    <td>
                        <input class="group-perm-add-folder-name" placeholder="{% trans "Select a folder"%}" /><img src="{{ MEDIA_URL }}img/add.png" alt="" title="Select a folder" class="perm-add-select-folder add vam" />
                        <input class="group-perm-add-folder-path" type="hidden" />
                    </td>
                    <td>
                        <select name="permission" class="group-perm-add-perm w100">
                        <option value="rw" selected="selected">{% trans "Read-Write"%}</option>
                        <option value="r">{% trans "Read-Only"%}</option>
                        </select>
                    </td>
                    <td>
                        <button class="perm-add-submit">{% trans "Submit" %}</button>
                    </td>
                </tr>
                {% if group_folder_perms %}
                {% for perm in group_folder_perms %}
                    <tr class="perm-item" data-group_id="{{ perm.group_id }}" data-path="{{ perm.path }}" data-perm="{{ perm.permission }}">
                        <td><a href="{% url 'view_group' perm.group_id %}">{{ perm.group_name }}</a></td>
                        <td><span><a href="{% url 'view_common_lib_dir' repo.id perm.path|urlencode|strip_slash %}">{{ perm.folder_name }}</a></span></td>
                        <td>
                            <div class="perm-change">
                              {% if perm.permission == 'rw' %}
                                <span class="perm-cur-value">{% trans "Read-Write" %}</span>
                              {% else %}
                                <span class="perm-cur-value">{% trans "Read-Only" %}</span>
                              {% endif %}
                                <img src="{{MEDIA_URL}}img/edit_12.png" alt="{% trans "Edit"%}" title="{% trans "Edit"%}" class="perm-edit-icon cspt vh" />
                            </div>
                            <select class="perm-toggle-select hide">
                                <option value="rw" {%if perm.permission == 'rw' %}selected="selected"{% endif %}>{% trans "Read-Write" %}</option>
                                <option value="r" {%if not perm.permission == 'rw' %}selected="selected"{% endif %}>{% trans "Read-Only"%}</option>
                            </select>
                        </td>
                        <td>
                            <img src="{{MEDIA_URL}}img/rm.png" class="perm-delete-btn op-icon vh" title="{% trans "Delete" %}" />
                        </td>
                    </tr>
                {% endfor %}
                {% endif %}
            </table>
        </div>
    </div>
    <div id="perm-add-jstree-wrap" class="file-choose-form hide">
        <h3>{% trans "Select a folder" %}</h3>
        <img src="{{MEDIA_URL}}img/loading-icon.gif" alt="" class="loading-tip" />
        <div id="perm-add-jstree" class="dir-tree-cont" data-repo_id="{{repo.id}}"></div>
        <button class="perm-add-jstree-select submit">{% trans "Submit" %}</button>
        <button class="simplemodal-close">{% trans "Cancel"%}</button>
        <p class="error hide"></p>
    </div>
</div>
{% endblock %}

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

var user_perm_add_tr = $('.user-perm-add-tr'),
    group_perm_add_tr = $('.group-perm-add-tr');

$('#user-tab').click(function() {
    group_perm_add_tr.addClass('hide');
});
$('#group-tab').click(function() {
    user_perm_add_tr.addClass('hide');
});

var group_list = [], group_name, group_id,
    user_input = $('#perm-add-user'),
    group_input = $('#perm-add-grp-name');

{% for group in request.user.joined_groups %}
group_name = '{{ group.group_name }}';
group_id = '{{ group.id }}';
group_list.push({value:group_id, label:group_name});
{% endfor %}

user_input.select2($.extend({
    width: '270px',
    placeholder: "{% trans "Search users or enter emails" %}",
    formatInputTooShort: "{% trans "Please enter 1 or more character" %}",
    formatNoMatches: "{% trans "No matches" %}",
    formatSearching: "{% trans "Searching..." %}",
    formatAjaxError: "{% trans "Loading failed" %}"
}, userInputOPtionsForSelect2('{% url 'search-user' %}')));

group_input.bind('autocompleteopen', function(e, ui) {
               var widget = group_input.autocomplete('widget');
               widget.css({'max-width':group_input.width() + 2 * parseInt(widget.css('padding-top')), 'max-height':$(window).height() + $(window).scrollTop() - group_input.offset().top - group_input.outerHeight()});
           })
           .autocomplete({
               source: group_list,
               select: function(event, ui) {
                   // prevent autocomplete from updating the textbox
                   event.preventDefault();
                   // manually update the textbox and hidden field
                   group_input.val(ui.item.label);
                   $('#perm-add-grp-id').val(ui.item.value);
               }
           });

$('#folder-perm-add-btn').click(function() {
    if (is_user_tab == true) {
        user_perm_add_tr.removeClass('hide');
        $('.user-perm-add-folder-name').val('');
        user_input.val('');
    } else {
        group_perm_add_tr.removeClass('hide');
        $('.group-perm-add-folder-name').val('');
        group_input.focus().val('');
    }
});

$('.perm-toggle-select').on('change', function() {
    var select = $(this),
        perm_item = select.parents('.perm-item'),
        path = perm_item.attr('data-path'),
        perm = select.val();

    if (is_user_tab == true) {
        var user = perm_item.attr('data-user'),
            data = {'user': user, 'path': path, 'perm': perm, 'type': 'modify'},
            url = '{% url 'set_user_folder_perm' repo.id %}';
    } else {
        var group_id = perm_item.attr('data-group_id'),
            data = {'group_id': group_id, 'path': path, 'perm': perm, 'type': 'modify'},
            url = '{% url 'set_group_folder_perm' repo.id %}';
    }

    perm_toggle(select, data, url)
});
$('.perm-delete-btn').on('click', function() {
    var perm_item = $(this).parents('.perm-item'),
        perm = perm_item.attr('data-perm'),
        path = perm_item.attr('data-path');

    if (is_user_tab == true) {
        var user = perm_item.attr('data-user'),
            data = {'user': user, 'path': path, 'perm': perm, 'type': 'delete'},
            url = '{% url 'set_user_folder_perm' repo.id %}';
    } else {
        var group_id = perm_item.attr('data-group_id'),
            data = {'group_id': group_id, 'path': path, 'perm': perm, 'type': 'delete'},
            url = '{% url 'set_group_folder_perm' repo.id %}';
    }

    $.ajax({
        url: url,
        type: 'POST',
        cache: false,
        dataType: 'json',
        beforeSend: prepareCSRFToken,
        data: data,
        success: function() {
            perm_item.remove();
            feedback("{% trans "Delete succeeded" %}", 'success');
        },
        error: ajaxErrorHandler
    });
});
$('.perm-add-submit').click(function() {
    var path, perm, data, url;
    if (is_user_tab == true) {
        var user = user_input.val();
        path = $('.user-perm-add-folder-path').val();
        if (!user || !path) {
            return false;
        }

        perm = $('.user-perm-add-perm').val();
        data = {'user': user, 'path': path, 'perm': perm, 'type': 'add'};
        url = '{% url 'set_user_folder_perm' repo.id %}';
    } else {
        var group_id = $('#perm-add-grp-id').val();
        path = $('.group-perm-add-folder-path').val();
        if (!group_id || !path) {
            return false;
        }

        perm = $('.group-perm-add-perm').val();
        data = {'group_id': group_id, 'path': path, 'perm': perm, 'type': 'add'};
        url = '{% url 'set_group_folder_perm' repo.id %}';
    }

    $.ajax({
        url: url,
        type: 'POST',
        cache: false,
        dataType: 'json',
        beforeSend: prepareCSRFToken,
        data: data,
        success: function() {
            location.reload();
        },
        error: ajaxErrorHandler
    });
});

$('.perm-add-select-folder').click(function() {
    $('#perm-add-jstree-wrap').modal({appendTo:'#main', autoResize:true, focus:false});
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
    render_jstree($('#perm-add-jstree'));
});

function selectClickHandler(event) {
    var path, folder_name, folder_path,
        path_array = event.data.path_array;

    if (is_user_tab == true) {
        folder_name = $('.user-perm-add-folder-name');
        folder_path = $('.user-perm-add-folder-path');
    } else {
        folder_name = $('.group-perm-add-folder-name');
        folder_path = $('.group-perm-add-folder-path');
    }
    if (path_array.length == 1) {
        path = path_array.shift();
        folder_name.val('/');
    } else {
        var root = path_array.shift(),
            path = root + path_array.join('/'),
            name = path.split('/');

        folder_name.val(name.pop());
    }

    folder_path.val(path);
    $.modal.close();
};

function render_jstree(container) {
    var base_path = '/', loading_tip = $('.loading-tip'),
        file_tree = new FileTree();

    container.data('site_root', '{{SITE_ROOT}}');
    container.data('repo_id', '{{repo.id}}');

    $.ajax({
        url: '{% url 'get_dirents' repo.id %}?path=' + e(base_path) + '&dir_only=true&all_dir=true',
        cache: false,
        dataType: 'json',
        success: function(data) {
            var json_data = [], children = [],
                repo_data = {'data': base_path, 'attr': {'root_node': true}, 'state': 'open'};

            for (var i = 0, len = data[0].length; i < len; i++) {
                children.push({ 'data': data[0][i], 'state': 'closed' });
            }
            if (children.length > 0) {
                $.extend(repo_data, {'children': children});
            }
            json_data.push(repo_data);

            loading_tip.hide();
            file_tree.renderDirTreeByRepo(container, json_data, selectClickHandler);
            container.removeClass('hide');
        },
        error: function() {
            var cur_repo = [{
                'data': base_path,
                'attr': {'root_node': true},
                'state': 'open'
            }];

            loading_tip.hide();
            renderDirTree(container, json_data);
            container.removeClass('hide');
        }
    });
}
$('.perm-add-jstree-select').click(function() {
    if($("#perm-add-jstree:has('.jstree-clicked')").length == 0) {
        $('#perm-add-jstree-wrap').find('.error')
                                  .removeClass('hide')
                                  .html('Please select a folder');
    }
});
</script>
{% endblock %}
