<form id="js-permissions-dialog-form">
    <input type="hidden" id="selected_permissions" value='{{ permissions|tojson|forceescape }}' name="selected_permissions">
    <input type="hidden" id="principal" value='{{ principal|tojson|forceescape }}'>
    <div class="permissions-dialog">
        <ul class="permissions">
            {% for code, tree_elem in permissions_tree|dictsort(reverse=true) recursive %}
                <li class="item">
                    <input type="checkbox" id="cb-{{ code }}"
                           class="circle-checkbox" {{ 'checked' if code in permissions or code == '_read_access' }}
                           {{ 'disabled' if code == '_read_access' }}
                           data-code="{{ code }}">
                    <label for="cb-{{ code }}" title="{{ tree_elem.description }}">{{ tree_elem.title }}</label>
                    {% if tree_elem.children %}
                        <ul class="permissions">
                            {{ loop(tree_elem.children|dictsort) }}
                        </ul>
                    {% endif %}
                </li>
            {% endfor %}
        </ul>
        <div class="toolbar f-j-end">
            <button type="submit" class="i-button big highlight" data-disabled-until-change>{% trans %}Save{% endtrans %}</button>
            <button class="i-button big" data-button-back>{% trans %}Cancel{% endtrans %}</button>
        </div>
    </div>
</form>
<script>
    (function () {
        'use strict';

        var $dialogForm = $('#js-permissions-dialog-form');
        function updateHiddenField() {
            var data = [];
            $dialogForm.find('input[type=checkbox]:checked').each(function() {
                var $this = $(this);
                // Only take into account the checked parents of the permissions tree
                if (!$this.parents('ul').siblings('input[type=checkbox]:checked').length) {
                    data.push($(this).data('code'));
                }
            });
            $dialogForm.find('#selected_permissions').val(JSON.stringify(data));
        }

        $dialogForm.on('submit', function(evt) {
            evt.preventDefault();
            var selectedPermissions = JSON.parse($('#selected_permissions').val());
            var principal = JSON.parse($('#principal').val());
            $('.permissions-widget').trigger('indico:permissionsChanged', [selectedPermissions, principal]);
            $dialogForm.trigger('ajaxDialog:close');
        }).on('change', function() {
            updateHiddenField();
        });

        // Prevent toggling children elements when parent is checked
        $dialogForm.find('input[type=checkbox]').on('click', function(evt) {
           if ($(this).closest('ul').siblings('input[type=checkbox]').is(':checked')) {
               evt.preventDefault();
           }
        });
    })();
</script>
