const EOF: string = "\n%-------------------% EOF %-------------------%\n\n";
const CONTENTS: string = "%----------------% Contents[%d] %--------------%\n\n";
const CONTENTS_PATTERN = /%----------------% Contents\[\d+\] %--------------%((?:.|\s)*?)%-------------------% EOF %-------------------%/gmu;
export default class ContentModel {
    parts: string[][];
    constructor(parts: string[][]) {
        this.parts = parts;
    }

    public toDisplay(): string {

        let text = "";
        if (this.parts.length > 1) {
            let i = 0;
            for (let part of this.parts) {
                text += CONTENTS.replace("%d", i.toString());
                for (let line of part) {
                    text += "  " + line + "\n";
                }
                text += EOF;
                i++;
            }
        } else if (this.parts.length == 1) {
            text = this.parts[0].join("\n");
        }
        return text;
    }

    public static fromDisplay(display: string): ContentModel {
        const parts: string[][] = [];
        let match;
        while ((match = CONTENTS_PATTERN.exec(display)) !== null) {
            let lines = match[1].split("\n").map(line => line.trim()).filter(line => line.length > 0);
            parts.push(lines);
        }
        if (parts.length == 0) {
            parts.push(display.split("\n").map(line => line.trim()));
        }

        return new ContentModel(parts);
    }
}