(function ($, Drupal) {
  Drupal.behaviors.pagedesigner_init_base_commands = {
    attach: function (context, settings) {
      $(document).on('pagedesigner-init-base-commands', function (e, editor) {

        editor.Commands.add('set-device-desktop', editor => {
          editor.setDevice('Desktop');
          jQuery('[data-responsive-options]').find('label').removeClass('active');
          jQuery('[data-responsive-options]').find('label[data-device="' + editor.getDevice() + '"]').addClass('active')
        });
        editor.Commands.add('set-device-tablet', editor => {
          editor.setDevice('Tablet');
          jQuery('[data-responsive-options]').find('label').removeClass('active');
          jQuery('[data-responsive-options]').find('label[data-device="' + editor.getDevice() + '"]').addClass('active')
        });
        editor.Commands.add('set-device-mobile', editor => {
          editor.setDevice('Mobile portrait');
          jQuery('[data-responsive-options]').find('label').removeClass('active');
          jQuery('[data-responsive-options]').find('label[data-device="' + editor.getDevice() + '"]').addClass('active')
        });

        // save component
        editor.Commands.add('save-component', (editor, sender) => {
          sender && sender.set('active', false);
          if (editor.getSelected()) {
            editor.getSelected().save();

            const openTraits = editor.Panels.getButton('sidebar', 'sidebar-open-traits');
            openTraits && openTraits.set('active', false);

            const openStyles = editor.Panels.getButton('sidebar', 'sidebar-open-styles');
            openStyles && openStyles.set('active', false);

            editor.select();
            editor.stopCommand('edit-component');
          }
        });

        // restore component
        editor.Commands.add('restore-component', (editor, sender) => {
          if (sender != editor) {
            sender && sender.set('active', false);
          }
          if (editor.getSelected() && (editor.getSelected().get('changed') || JSON.stringify(editor.getSelected().serialize().styles) != JSON.stringify(editor.getSelected().get('previousVersion').styles))) {
            if (confirm(Drupal.t("Do you want to cancel your changes?"))) {
              editor.getSelected().restore();
              editor.select();
              editor.stopCommand('edit-component');
            }
          } else {
            editor.select();
            editor.stopCommand('edit-component');
          }
        });

        // delete component
        editor.Commands.add('tlb-delete-component', {
          run(editor) {
            if (editor.getSelected() && confirm(Drupal.t('Do you want to delete the component?'))) {
              editor.getSelected().set('changed', false);
              editor.getSelected().delete();
              editor.runCommand('core:component-delete');
              editor.select();
              const openTraits = editor.Panels.getButton('sidebar', 'sidebar-open-traits');
              openTraits && openTraits.set('active', false);
              const openStyles = editor.Panels.getButton('sidebar', 'sidebar-open-styles');
              openStyles && openStyles.set('active', false);
            }
          }
        });

        // top menu
        editor.Commands.add('sw-visibility', {
          run(ed) {
            ed.Canvas.getBody().classList.add(this.ppfx + 'dashed');
          },
          stop(ed) {
            ed.Canvas.getBody().classList.remove(this.ppfx + 'dashed');
          }
        });

        editor.Commands.add('tlb-copy-component', {
          run(ed) {
            var component = editor.getSelected();
            if (component) {
              if (component.get('changed')) {
                if (confirm(Drupal.t("Do you want to save your changes?"))) {
                  component.save();
                } else {
                  component.restore();
                }
              }
              if (component && confirm(Drupal.t('Do you want to copy the element?'))) {
                component.clone();
              }
            }
          }
        });

        // help
        editor.Commands.add('open-help', {
          run(editor) {
            const lm = editor.LayerManager;
            const pn = editor.Panels;
            if (!this.help) {
              const id = 'views-container';
              const help = document.createElement('div');
              const panels = pn.getPanel(id) || pn.addPanel({ id });

              help.append($('<div>' + drupalSettings.pagedesigner.help_text + '</div>').get(0));
              panels.set('appendContent', help).trigger('change:appendContent');
              this.help = help;
            }
            this.help.style.display = 'block';

            editor.Panels.getPanel('views-container').set('visible', true);
          },
          stop() {
            const help = this.help;
            help && (help.style.display = 'none');
            editor.Panels.getPanel('views-container').set('visible', false);
          }
        });

        // publish
        editor.Commands.add('publish-page', {
          run(editor) {
            if (Drupal.frontendpublishing) {
              Drupal.frontendpublishing.showTransitionDialog(window.drupalSettings.path.nid, window.drupalSettings.path.currentLanguage, true);
            } else if (Drupal.pagetree) {
              $('#ptPublishModal').find('#revisionMessage').val("");
              $('#ptPublishModal').dialog({
                resizable: false,
                height: "auto",
                width: 400,
                modal: true,
                buttons: {
                  "Publish page": (function (action) {
                    return function () {
                      $(this).dialog("close");
                      var message = $('#ptPublishModal').find("textarea").val();
                      Drupal.pagetree.publishNode(window.drupalSettings.path.nid, window.drupalSettings.path.currentLanguage, message);
                    }
                  })($(this)),
                  Cancel: function () {
                    $(this).dialog("close");
                  }
                }
              });
            }
          }
        }
        );

        // unpublish
        editor.Commands.add('unpublish-page', {
          run(editor) {
            if (Drupal.frontendpublishing) {
              Drupal.frontendpublishing.showTransitionDialog(window.drupalSettings.path.nid, window.drupalSettings.path.currentLanguage, false);
            } else if (Drupal.pagetree) {
              $('#ptUnpublishModal').find('#revisionMessage').val("");
              $('#ptUnpublishModal').dialog({
                resizable: false,
                height: "auto",
                width: 400,
                modal: true,
                buttons: {
                  "Unpublish page": (function (action) {
                    return function () {
                      $(this).dialog("close");
                      var message = $('#ptUnpublishModal').find("textarea").val();
                      Drupal.pagetree.unpublishNode(window.drupalSettings.path.nid, window.drupalSettings.path.currentLanguage, message);
                    }
                  })($(this)),
                  Cancel: function () {
                    $(this).dialog("close");
                  }
                }
              });
            }
          }
        });


        // settings
        editor.Commands.add('open-settings', {
          run(editor) {
            window.open(window.drupalSettings.path.baseUrl + window.drupalSettings.path.pathPrefix + 'node/' + window.drupalSettings.path.nid + '/edit');
          },
        });

        // preview
        editor.Commands.add('open-preview', {
          run(editor) {
            let previewIframe = $('<iframe class="gjs-mdl-preview-iframe" src="/node/' + window.drupalSettings.path.nid + '/"/>')[0];

            editor.Modal.setTitle(Drupal.t('Preview'));
            editor.Modal.setContent(previewIframe);
            editor.Modal.open();

            window.setTimeout(function () {
              let iframe = document.querySelector('.gjs-mdl-preview-iframe');
              iframe.contentWindow.jQuery('body').css('padding', 0);
              iframe.contentWindow.jQuery('#toolbar-administration, .pd-edit-icon, .pt-pagetree-icon').remove();
            }, 2000)
          }
        });




        // edit component
        editor.Commands.add('edit-component', {
          run(editor) {
            if (editor.getSelected()) {
              const openTraits = editor.Panels.getButton('sidebar', 'sidebar-open-traits');
              const openStyles = editor.Panels.getButton('sidebar', 'sidebar-open-styles');
              openStyles && openStyles.set('disable', false);

              if (editor.getSelected().get('traits').map(a => a.get('type')).filter(e => e !== 'cell').length > 0) {
                openTraits && openTraits.set('active', true);
                openTraits && openTraits.set('disable', false);
              } else {
                openStyles && openStyles.set('active', true);
              }

            }
          },
          stop() {
            editor.select();
            const openTraits = editor.Panels.getButton('sidebar', 'sidebar-open-traits');
            openTraits && openTraits.set('active', false);
            openTraits && openTraits.set('disable', true);

            const openStyles = editor.Panels.getButton('sidebar', 'sidebar-open-styles');
            openStyles && openStyles.set('active', false);
            openStyles && openStyles.set('disable', true);
          }
        });
      });
    }
  };
})(jQuery, Drupal);
