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

type sourceType = {
  _id?: string;
  file?: {
    url?: string;
  };
};

export class DragAddCtrl extends ModuleControl<EditorModule> {
  dragingCompKey = "";
  dragingCompData: sourceType = {};

  _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();
    }
  }

  updateCompData(data: object) {
    this.dragingCompData = data;
  }

  initEvent() {
    const scope = this;

    async 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;
      await scope.actions.dragCompToDesign(e, scope.dragingCompKey as any);
      if (
        scope.dragingCompData?._id &&
        (scope.dragingCompKey == "Image" || scope.dragingCompKey == "Video")
      ) {
        scope.store.currComp.value.url = scope.dragingCompData?.file?.url;
        scope.dragingCompData = {};
      }
      scope.dragingCompKey = "";
    }

    document.addEventListener("mouseup", mouseup);

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