/**
 * @file
 * Javascript functionality for component tree structure.
 */

(function ($, Drupal, once) {

  'use strict';

  Drupal.componentTreeStructure = Drupal.componentTreeStructure || {};
  Drupal.behaviors.tree_structure = {
    attach: function (context) {
      Drupal.componentTreeStructure.tree_structure(context);
    }
  }
  Drupal.componentTreeStructure.tree_structure = function (context) {
    const $tree_structure = $(once('treeStructureItems', '.field--name-field-components.field--type-entity-reference > div', context));
    if ($tree_structure.length > 0) {
      $tree_structure.each(function () {
        const $this = $(this);
        let id = $this.find('.component-wrapper--type-tree_structure').attr('id');
        const items = drupalSettings['components']['tree_structure']['items'];
        const n_parent = drupalSettings['components']['tree_structure']['items'].length;
        const tree = {};
        let dict_parent = {};
        for (let i = 0; i < n_parent; i++) {
          let dict = {};
          if (items[i]['leaves'].length == 0) {
            dict_parent['parent--' + id + '-' + i] = '';
          } else {
            for (let j = 0; j < items[i]['leaves'].length; j++) {
              dict['leaf--' + id + '-' + i + '-' + j] = '';
            }
            dict_parent['parent--' + id + '-' + i] = dict;
          }
        }

        tree['root--' + id] = dict_parent;

        let params = {}
        params['root--' + id] = {
          trad: drupalSettings['components']['tree_structure']['root'],
          styles: {'box-shadow': '0 0 15px 2px blue'}
        };
        for (let i = 0; i < n_parent; i++) {
          params['parent--' + id + '-' + i] = {trad: items[i]['parent']};
        }
        for (let i = 0; i < n_parent; i++) {
          for (let j = 0; j < items[i]['leaves'].length; j++) {
            params['leaf--' + id + '-' + i + '-' + j] = {trad: items[i]['leaves'][j]['value']};
          }
        }


        treeMaker(tree, {
          id: 'myTree--' + id, card_click: function (element) {
          },
          treeParams: params,
          'link_width': '4px',
          'link_color': '#ff5259',
        });

      })
    }
  }

})(jQuery, Drupal, once);
