import { isArray, contains } from 'underscore';

export default function (editor) {
  // grapesjs 在 destroy 时，没有正确清理掉 “backspace, delete” 的快捷键绑定，导致切换项目时，重复绑定快捷键
  const Keymaps = editor.Keymaps;

  editor.on('keymap:remove', function(keymaps) {
    if (keymaps.id === 'core:component-delete') {
      Keymaps.keymaster.unbind('backspace');
      Keymaps.keymaster.unbind('delete');
    }
  });
  
  editor.Commands.extend('core:copy', {
    run(ed) {
      const em = ed.getModel();
      const models = [...ed.getSelectedAll()];
      models.length && em.set('clipboard', models);
      
      /**
       * 新增逻辑, 挂载在window上
       * copyComponent：组件配置
       * copyComponentUrl：拷贝组件所在模板地址
       */
      window.SPFrontPanel.copyComponent = models;
      window.SPFrontPanel.copyComponentUrl = window.location.href;
    }
  });

  editor.Commands.extend('core:paste', {
    run(ed) {
      const em = ed.getModel();
      const copyComponentUrl = _.get(window.SPFrontPanel, 'copyComponentUrl', '');
      const copyComponent = _.get(window.SPFrontPanel, 'copyComponent', null);
      let clp = em.get('clipboard');

      if (copyComponent && copyComponentUrl && copyComponentUrl !== window.location.href) {
        clp = [...copyComponent];
        window.SPFrontPanel.copyComponent = null;
        window.SPFrontPanel.copyComponentUrl = '';
      }

      const selected = ed.getSelected();
  
      if (clp && selected) {
        ed.getSelectedAll().forEach(comp => {
          if (!comp) return;
          const coll = comp.collection;
          const at = coll.indexOf(comp) + 1;
          const copyable = clp.filter(cop => cop.get('copyable'));
          let added;
  
          if (contains(clp, comp) && comp.get('copyable')) {
            added = coll.add(comp.clone(), { at });
          } else {
            added = coll.add(copyable.map(cop => cop.clone()), { at });
          }
  
          added = isArray(added) ? added : [added];
          added.forEach(add => ed.trigger('component:paste', add));
        });
  
        selected.emitUpdate();
      }
    }
  });
}