/**
 * OrderedList Node Extension
 * 有序列表节点
 */

import { NodeExtension } from '../../core/Extension';
import { wrappingInputRule } from 'prosemirror-inputrules';
import { wrapInList, liftListItem, sinkListItem } from 'prosemirror-schema-list';
import type { NodeSpec, Schema, InputRule, Command } from '../../core/types';

export class OrderedList extends NodeExtension {
  get name() {
    return 'orderedList';
  }

  get schema(): NodeSpec {
    return {
      content: 'listItem+',
      group: 'block',
      attrs: {
        order: { default: 1 },
      },
      parseDOM: [
        {
          tag: 'ol',
          getAttrs(dom) {
            const element = dom as HTMLElement;
            return {
              order: element.hasAttribute('start')
                ? parseInt(element.getAttribute('start') || '1', 10)
                : 1,
            };
          },
        },
      ],
      toDOM(node) {
        return node.attrs.order === 1
          ? ['ol', { class: 'editor-ordered-list' }, 0]
          : ['ol', { class: 'editor-ordered-list', start: node.attrs.order }, 0];
      },
    };
  }

  inputRules(schema: Schema): InputRule[] {
    const type = schema.nodes[this.name];
    if (!type) return [];

    return [
      // 1. 开头转换为有序列表
      wrappingInputRule(
        /^(\d+)\.\s$/,
        type,
        (match) => ({ order: parseInt(match[1], 10) }),
        (match, node) => node.childCount + node.attrs.order === parseInt(match[1], 10)
      ),
    ];
  }

  keys(schema: Schema): Record<string, Command> {
    const listItemType = schema.nodes.listItem;
    if (!listItemType) return {};

    return {
      'Tab': sinkListItem(listItemType),
      'Shift-Tab': liftListItem(listItemType),
    };
  }
}

export default OrderedList;
