/**
 * TableCell Node Extension
 * 表格单元格节点
 */

import type { NodeSpec } from '../../core/types';
import { NodeExtension } from '../../core/Extension';

export interface TableCellOptions {
  /** 单元格最小宽度 */
  cellMinWidth?: number;
}

export class TableCell extends NodeExtension<TableCellOptions> {
  get name(): string {
    return 'tableCell';
  }

  get schema(): NodeSpec {
    return {
      content: 'block+',
      attrs: {
        colspan: { default: 1 },
        rowspan: { default: 1 },
        header: { default: false },
        colwidth: { default: null },
      },
      tableRole: 'cell',
      isolating: true,
      parseDOM: [
        {
          tag: 'td',
          getAttrs(dom: HTMLElement) {
            const colspan = dom.getAttribute('colspan');
            const rowspan = dom.getAttribute('rowspan');
            const colwidth = dom.getAttribute('data-colwidth');

            return {
              colspan: colspan ? parseInt(colspan, 10) : 1,
              rowspan: rowspan ? parseInt(rowspan, 10) : 1,
              header: false,
              colwidth: colwidth ? colwidth.split(',').map((w) => parseInt(w, 10)) : null,
            };
          },
        },
        {
          tag: 'th',
          getAttrs(dom: HTMLElement) {
            const colspan = dom.getAttribute('colspan');
            const rowspan = dom.getAttribute('rowspan');
            const colwidth = dom.getAttribute('data-colwidth');

            return {
              colspan: colspan ? parseInt(colspan, 10) : 1,
              rowspan: rowspan ? parseInt(rowspan, 10) : 1,
              header: true,
              colwidth: colwidth ? colwidth.split(',').map((w) => parseInt(w, 10)) : null,
            };
          },
        },
      ],
      toDOM(node) {
        const { colspan, rowspan, header, colwidth } = node.attrs;
        const tag = header ? 'th' : 'td';

        const attrs: Record<string, string> = {
          class: header ? 'editor-table-header' : 'editor-table-cell',
        };

        if (colspan !== 1) {
          attrs.colspan = String(colspan);
        }
        if (rowspan !== 1) {
          attrs.rowspan = String(rowspan);
        }
        if (colwidth) {
          attrs['data-colwidth'] = colwidth.join(',');
          attrs.style = `width: ${colwidth.reduce((a: number, b: number) => a + b, 0)}px`;
        }

        return [tag, attrs, 0];
      },
    };
  }
}

export default TableCell;
