require(['jquery', "../../../webjars/xwiki-platform-tree-webjar/11.5/require-config.min.js"], function($) {
  $('.paths').on('click', '.path-delete', function(event) {
    event.preventDefault();
    $(this).closest('.path').remove();
  }).on('click', '.path-add', function(event) {
    event.preventDefault();
    $('.location-picker.modal').prop('modalTrigger', $(this)).modal();
  });

  var getLocalSpaceReference = function(nodeId) {
    var separatorIndex = nodeId.indexOf(':');
    var nodeType = nodeId.substr(0, separatorIndex);
    var nodeStringReference = nodeId.substr(separatorIndex + 1);
    var currentDocRef = XWiki.currentDocument.getDocumentReference();
    var nodeReference = XWiki.Model.resolve(nodeStringReference, XWiki.EntityType.byName(nodeType), currentDocRef);
    var spaceReference = nodeReference.extractReference(XWiki.EntityType.SPACE);
    var localSpaceReference = spaceReference.relativeTo(currentDocRef.extractReference(XWiki.EntityType.WIKI));
    return XWiki.Model.serialize(localSpaceReference);
  };

  var addLocation = function(value, paths) {
    var template = paths.find('.path.hidden');
    var newPath = template.clone().removeClass('hidden').insertBefore(template);
    newPath.find('input').prop('disabled', false).val(value);
    $.post(XWiki.currentDocument.getURL('get'), {
      'xpage': 'hierarchy_reference',
      // The passed reference is resolved as document reference.
      'reference': value + '.WebHome',
      'local': true,
      'selfIsActive': false
    }, function(data) {
      newPath.find('.breadcrumb').replaceWith(data);
    });
  };

  $('.location-picker.modal').on('xwiki:locationTreePicker:select', function(event, data) {
    var trigger = $(this).prop('modalTrigger');
    data.tree.get_selected().map(getLocalSpaceReference).forEach(function(localReference) {
      addLocation(localReference, trigger.closest('.paths'));
    });
  });

  // Location Tree Picker
  require(['tree'], function($) {
    $('.location-picker.modal').each(function() {
      var modal = $(this);
      var treeElement = modal.find('.location-tree');
      var selectButton = modal.find('.modal-footer .btn-primary');

      modal.on('shown.bs.modal', function(event) {
        if (!$.jstree.reference(treeElement)) {
          // Initialize the tree and hook the event listeners.
          treeElement.xtree({
            core: {
              multiple: true
            }
          }).on('changed.jstree', function(event, data) {
            selectButton.prop('disabled', data.selected.size() === 0);
          }).on('dblclick', '.jstree-anchor', function() {
            selectButton.click();
          });
        }
      });

      selectButton.click(function() {
        modal.modal('hide');
        modal.triggerHandler('xwiki:locationTreePicker:select', {
          'tree': $.jstree.reference(treeElement)
        });
      });
    });
  });
});
