import ClassName from "../../container/ClassName";
import { Injectable } from "../../container/Injectable";

@ClassName('MDUtils')
@Injectable()
export default class MDUtils {
    /**
     * 解析 Markdown 内容
     * @param {String} from
     * @param {Number} max_line 最大行数，默认500
     * @returns {HTMLDivElement}
     */
    public parse(from: string, max_line?: number): HTMLElement {
        max_line = max_line || 500;
        const base = document.createElement('div');
        let lines = from.split('\n');
        if (lines.length > max_line) {
            lines = lines.slice(0, max_line);
            lines.push("...");
        }

        let prev = '';
        let child_cont;
        lines.forEach(line => {
            if (line.trim() === '') return;
            let node;
            let spl = line.split(' ');
            let md_flag = spl[0];

            switch (md_flag) {
                // 标题
                case '#':
                case '##':
                case '###':
                    if (prev === 'li') {
                        child_cont = null;
                    }
                    prev = 'h' + (md_flag.length + 1);
                    node = document.createElement(prev);
                    node.innerText = line.slice(md_flag.length + 1);
                    base.append(node);
                    return;
                // 列表
                case '-':
                    if (prev !== 'li') {
                        child_cont = document.createElement('ul');
                        if (!base.contains(child_cont)) base.append(child_cont);
                    }
                    prev = 'li';
                    node = document.createElement(prev);
                    node.innerText = line.slice(2);
                    child_cont.append(node);
                    return;
            }
            prev = 'p';
            node = document.createElement(prev);
            node.innerText = line.trim();
            base.append(node);
        })
        return base;
    }
}