import { ModuleControl } from "queenjs";
import { EditorModule } from "../../module";

export class DragAddCtrl extends ModuleControl<EditorModule> {
  dragingCompKey = "";

  _cancel?: () => void;
  _mouseUping = false;

  updateCompKey(k: string) {
    if (this._mouseUping) return;

    const isSame = k == this.dragingCompKey;
    this.dragingCompKey = k;
    if (!isSame && k) {
      if (this._cancel) this._cancel();
      this._cancel = this.initEvent();
    }
  }

  initEvent() {
    const scope = this;

    function mouseup(e: MouseEvent) {
      console.log("mouseup=>", scope.dragingCompKey);
      scope._mouseUping = true;
      setTimeout(() => {
        scope._mouseUping = false;
      }, 1000);

      if (scope._cancel) scope._cancel();

      if (!scope.dragingCompKey) return;
      scope.actions.dragCompToDesign(e, scope.dragingCompKey as any);
      scope.dragingCompKey = "";
    }

    document.addEventListener("mouseup", mouseup);

    return () => {
      document.removeEventListener("mouseup", mouseup);
      scope._cancel = undefined;
    };
  }
}
