// components
(function ($, Drupal) {

  function init_component(editor) {

    // add new component type layout
    editor.DomComponents.addType('layout', {
      extend: 'row',
      model: {
        create() {
          editor.spinner.enable()
          var component = this;
          var parent = this.parent();
          var index = this.index();

          var data = {
            original: editor.BlockManager.get(component.attributes.type).attributes.additional.root,
            container: component.getContainer(),
            parent: parent.get('entityId')
          };

          this.remove();

          Drupal.restconsumer.post('/pagedesigner/clone/', data).done(function (response) {
            var markup = response.filter(cmd => cmd.command == 'pd_markup')[0].data;
            var styles = response.filter(cmd => cmd.command == 'pd_styles')[0].data;

            parent.components().add(markup, { at: index });
            editor.Parser.parseCss(styles).forEach(function (rule) {
              if (!(Object.keys(rule.style).length === 0 && rule.style.constructor === Object)) {
                editor.CssComposer.setIdRule(rule.selectors[0], rule.style, { mediaText: rule.mediaText })
              }
            });
            parent.save();
            editor.spinner.disable()
          });
        }
      }
    });
  }

  function init_command(editor) {

    // command create layout
    editor.Commands.add('open-modal-create-layout', {
      run(editor, sender) {

        var component = editor.getSelected();

        if (component.get('changed')) {
          if (confirm(Drupal.t("Do you want to save your changes?"))) {
            component.save();
          } else {
            component.restore();
          }
        }

        // open modal
        editor.Modal.setTitle('Create layout form component');
        var modal = $('#pdCreateLayout');
        if (modal.length == 0) {
          modal = $(`
            <div id="pdCreateLayout" title="Create layout form component" style="display: none;">
              <p>
              <i class="fas fa-copy" style="float:left; margin:12px 12px 20px 0;"></i>
              The component will be saved as a layout. Please give a name and a description.
              </p>
              <h4>Name*</h4>
              <input type="text" name="name" value="" />
              <h4>Description</h4>
              <textarea id="revisionMessage" name="description" style="height:150px;width: 100%;"></textarea>

            </div >
            `);
          $('body').append(modal);
        }
        modal.dialog({
          resizable: false,
          height: "auto",
          width: 400,
          modal: true,
          buttons: {
            "Save layout": (function (action) {
              return function () {
                var name = modal.find("input[name=name]");
                if (name.val() == '') {
                  name.css('border', '2px solid red');
                  return;
                }
                var description = modal.find("textarea[name=description]");
                // var includeContent = modal.find("input[name=includecontent]");
                Drupal.restconsumer.post('/pagedesigner/layout', {
                  original: component.get('entityId'),
                  name: name.val(),
                  description: description.val(),
                  // include_content: includeContent.get(0).checked,
                }).done(function (response) {

                  var pattern_id = 'layout' + response[0].id[0].value;
                  var layout_name = response[0].name[0].value;

                  editor.DomComponents.addType(pattern_id, {
                    extend: 'layout',
                    model: {
                      defaults: {
                        name: layout_name,
                        traits: [],
                        stylable: false,
                        styles: [],
                        toggable_classes: [],
                        styling_options: []
                      }
                    }
                  });

                  editor.BlockManager.add(pattern_id, {
                    additional: {
                      category: 'Layouts',
                      icon: 'fas fa-cube',
                      layout: response[0].id[0].value,
                      markup: '<div></div>',
                      pagedesigner: 1,
                      root: component.get('entityId'),
                      type: 'layout',
                    },
                    label: layout_name,
                    pattern: {
                      type: pattern_id,
                      template: '<div></div>'
                    },
                    content: '<div data-gjs-type="' + pattern_id + '"></div>',
                    preview: {},
                    category: 'Layouts',
                    attributes: {
                      class: 'fas fa-cube'
                    }
                  });

                  component.set('changed', false);
                });
                $(this).dialog("close");
              }
            })($(this)),
            Cancel: function () {
              $(this).dialog("close");
            }
          }
        });
      }
    });
  }

  Drupal.behaviors.pagedesigner_layouts_components = {
    attach: function (context, settings) {
      $(document).on('pagedesigner-init-components', function (e, editor) {
        init_component(editor);
      });
    }
  };

  Drupal.behaviors.pagedesigner_layouts_commands = {
    attach: function (context, settings) {
      $(document).on('pagedesigner-init-commands', function (e, editor) {
        init_command(editor);
      });
    }
  };

})(jQuery, Drupal);
