import $ from 'jquery';

const ALIGNMENT_TYPE = { horizontal: 'horizontal', vertical: 'vertical' };
const evName = 'dmode';

class AlignmentGuideLine {
  constructor(type) {
    this.type = type;

    this.$el = this.createEl();
  }

  createEl() {
    const $el = $('<div class="fullsize-guide-line"></div>');
    $el.css({
      position: 'absolute',
      'background-color': 'red',
      'z-index': 1
    });
    return $el;
  }

  hide() {
    this.$el.hide();
  }

  getEl() {
    return this.$el[0];
  }

  update({ width, height, left, top }) {
    this.$el.width(width).height(height).css({ left: `${left}px`, top: `${top}px` }).show();
  }
}

export default function (editor) {
  let fullWidthGuide = null;
  let fullHeightGuide = null;
  let hideTimer = null;

  const hideGuide = () => {
    fullWidthGuide && fullWidthGuide.hide();
    fullHeightGuide && fullHeightGuide.hide();
  }

  // 前面板，拖入组件时，定位到鼠标位置
  editor.editor.on(`${evName}:active`, (options) => {
    if (hideTimer) {
      clearTimeout(hideTimer);
    }
    const { target, guidesTarget, guidesStatic, guide, matched, size, elGuideInfo, elGuideInfoCnt, posFirst, posSecond } = options;

    /*
     * 在 elGuideInfo 的 parentNode 中添加一个跟 elGuideInfo 同级的基准线
     * 水平对齐时添加 fullWidthGuide，垂直对齐时添加 fullHeightGuide
     */
    const parent = elGuideInfo.parentNode;
    let width = 0;
    let height = 0;
    let left = 0;
    let top = 0;

    switch (guide.type) {
      case 't':
      case 'b':
      case 'y':
        if (!fullWidthGuide) {
          fullWidthGuide = new AlignmentGuideLine(ALIGNMENT_TYPE.horizontal);
          parent.appendChild(fullWidthGuide.getEl());
        }

        // 水平基准线的宽度为 guide（当前选中的组件）宽度 + matched（基准组件）宽度 + 间距 
        width = guide.originRect.width + matched.originRect.width + size;
        height = 1;
        left = Math.min(guide.originRect.left, matched.originRect.left);
        top = posFirst;
        fullWidthGuide.update({ width, height, left, top });
        break;
      case 'l':
      case 'r':
      case 'x':
        if (!fullHeightGuide) {
          fullHeightGuide = new AlignmentGuideLine(ALIGNMENT_TYPE.vertical);
          parent.appendChild(fullHeightGuide.getEl());
        }

        // 垂直基准线的高度为 guide（当前选中的组件）高度 + matched（基准组件）高度 + 间距 
        width = 1;
        height = guide.originRect.height + matched.originRect.height + size;
        left = posFirst;
        top = Math.min(guide.originRect.top, matched.originRect.top);
        fullHeightGuide.update({ width, height, left, top });
        break;
    }

    hideTimer = setTimeout(hideGuide, 100);
  });

  editor.editor.on(`${evName}:end`, hideGuide);
}
