import { customSVG } from '../../configuration/constants';

export default (editor, opt = {}) => {
  const domc = editor.DomComponents;
  const defaultType = domc.getType('default');
  const defaultModel = defaultType.model;
  const defaultView = defaultType.view;

  // DEMO - 自定义svg
  domc.addType(customSVG, {
    model: defaultModel.extend({
      defaults: {
        ...defaultModel.prototype.defaults,
        resizable: true,
        dmode: 'absolute',
        childrenSelectable: false,
        highlightable: false,
        droppable: false,
        name: 'svg',
        traits: [
          {
            label: 'width',
            changeProp: 1,
            name: 'width',
            type: 'number'
          }, {
            label: 'height',
            changeProp: 1,
            name: 'height',
            type: 'number'
          }, {
            label: 'viewBox',
            changeProp: 1,
            name: 'viewBox'
          }, {
            label: 'innerSvg',
            changeProp: 1,
            type: 'code',
            name: 'innerSvg'
          }
        ],
        "width": 40,
        "height": 40,
        "viewBox": '0 0 40 40',
        "innerSvg": "<circle cx='20' cy='20' r='10' fill='darkred'/>",
        script: function () {
          const width = '{[ width ]}';
          const height = '{[ height ]}';
          const viewBox = '{[ viewBox ]}';
          const innerSvg = ('{[ innerSvg ]}').replace(/[\r\n]/g, "");
          let svg = "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' viewBox='" + viewBox + "' width='100%' height='100%'>" + innerSvg + "</svg>";

          $(this).attr('style', 'width:' + width + 'px; height:' + height + 'px;');
          $(this).html(svg);
        }
      }
    }, {
      isComponent(el) {
        if (el.getAttribute && el.getAttribute('data-gjs-type') == customSVG) {
          return { type: customSVG };
        }
      }
    }),
    view: defaultView.extend({
      init() {
        const evn = 'change:width change:height change:viewBox change:innerSvg';
        this.listenTo(this.model, evn, this.updateScript);
        this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
      },
    })
  });
}
