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

type IHotKeyItem = {
  hotKey: string;
  action: (this: EditorModule, key: string) => void;
};

export class HotKeyCtrl extends ModuleControl<EditorModule> {
  // 热键配置
  hotKeys = this.defineHotKeys([
    // 取消选中
    {
      hotKey: "esc",
      action() {
        this.actions.pickComp("");
      },
    },
    // 切换到父组件
    {
      hotKey: "ctrl+up",
      action() {
        this.actions.pickParentComp(this.store.currCompId);
      },
    },
    // 删除当前组件
    {
      hotKey: "Backspace,del",
      action() {
        this.actions.removeComp(this.store.currCompId);
      },
    },
    {
      hotKey: "q,w,a,s,d,e",
      action(key) {
        // this.actions.removeComp(this.store.currCompId);
        // console.log("image hot key down", key);
        this.actions.handleImageHotKey(key);
      },
    },
    // 回退
    {
      hotKey: "ctrl+z",
      action() {
        this.controls.historyCtrl.history.undo();
      },
    },
    // 重做
    {
      hotKey: "ctrl+shift+z",
      action() {
        this.controls.historyCtrl.history.redo();
      },
    },
  ]);

  init() {
    const { module, hotKeys } = this;

    hotkeys(
      hotKeys.map((d) => d.hotKey).join(","),
      module.moduleName,
      function (event, handler) {
        event.preventDefault();

        const hotAct = hotKeys.find((d) =>
          d.hotKey.split(",").includes(handler.key)
        );
        hotAct?.action.call(module, handler.key);
      }
    );
    hotkeys.setScope(module.moduleName);
  }

  destroy() {
    hotkeys.deleteScope(this.module.moduleName);
  }

  defineHotKeys<T extends IHotKeyItem[]>(hotKeys: T) {
    return hotKeys;
  }
}
