import { EditorView, keymap } from '@codemirror/view';
import { defaultKeymap, indentSelection, indentWithTab, undo, history } from '@codemirror/commands';
import { indentUnit } from '@codemirror/language';
import prettier from 'prettier';
// import parserBabel from 'prettier/plugins/babel';
import parserEstree from 'prettier/plugins/estree';
// import parserHtml from 'prettier/plugins/html';
import parserTypescript from 'prettier/plugins/typescript';
import { autocompletion, CompletionContext } from '@codemirror/autocomplete';

// 格式化函数
// Function to format the code using Prettier
async function formatCode(view: EditorView) {
  const editor = view;
  const code = editor.state.doc.toString();
  try {
    const formattedCode = await prettier.format(code, {
      parser: 'typescript',
      plugins: [parserEstree, parserTypescript],
    });

    editor.dispatch({
      changes: {
        from: 0,
        to: editor.state.doc.length,
        insert: formattedCode.trim(),
      },
    });
  } catch (error) {
    console.error('Error formatting code:', error);
  }
}
// export const TabFn = (view: EditorView) => {
//   const { state } = view;
//   const selection = state.selection.main;
//   // 判断是否存在补全上下文
//   if (state.field(autocompletion).active?.length) {
//     // 插入当前选中的补全内容
//     const active = state.field(autocompletion).active[0];
//     const selected = active?.options[active.selected]?.label;
//     if (selected) {
//       view.dispatch({
//         changes: { from: selection.from, to: selection.to, insert: selected },
//       });
//       return true;
//     }
//   }
//   return false;
// };

// 自定义 Tab 键行为
function customIndentWithTab(view: EditorView) {
  const { state, dispatch } = view;
  const { from, to } = state.selection.main;
  const _indentUnit = state.facet(indentUnit) as string;

  // 计算插入的缩进
  const indent = _indentUnit.repeat(1);

  dispatch({
    changes: { from, to, insert: indent },
    selection: { anchor: from + indent.length },
  });

  return true; // 表示按键事件被处理
}
export const formatKeymap = keymap.of([
  {
    // bug, 必须小写
    key: 'alt-shift-f', // 快捷键绑定
    // mac: 'cmd-shift-f',
    run: (view) => {
      formatCode(view);
      return true; // 表示按键事件被处理
    },
  },
  {
    key: 'Tab',
    run: customIndentWithTab, // 使用自定义的缩进函数
  },
  {
    key: 'Ctrl-z', // Windows 撤销快捷键
    // key: 'Alt-z',
    mac: 'Cmd-z', // Mac 撤销快捷键
    run: (view) => {
      console.log('undo', view);
      return undo(view); // 表示按键事件被处理
    },
  },
  ...defaultKeymap, // 默认快捷键
]);
// console.log('formatKeymap', defaultKeymap);
