package markup;

import java.util.List;

/**
 * @author Nikita Doschennikov (me@fymio.us)
 */
public abstract class AbstractMarkup implements Markdown, Html, Tex {

    protected final List<? extends Markup> items;
    private final String highlightMarkdown;
    private final String highlightHtml;
    private final String highlightTexOpen;
    private final String highlightTexClose;

    protected AbstractMarkup(
        List<? extends Markup> items,
        String highlightMarkdown,
        String highlightHtml,
        String highlightTexOpen,
        String highlightTexClose
    ) {
        this.items = items;
        this.highlightMarkdown = highlightMarkdown;
        this.highlightHtml = highlightHtml;
        this.highlightTexOpen = highlightTexOpen;
        this.highlightTexClose = highlightTexClose;
    }

    @Override
    public void toMarkdown(StringBuilder sb) {
        sb.append(highlightMarkdown);
        for (Markup item : items) {
            item.toMarkdown(sb);
        }
        sb.append(highlightMarkdown);
    }

    @Override
    public void toHtml(StringBuilder sb) {
        if (!highlightHtml.isEmpty()) {
            sb.append("<").append(highlightHtml).append(">");
        }
        for (Markup item : items) {
            item.toHtml(sb);
        }
        if (!highlightHtml.isEmpty()) {
            sb.append("</").append(highlightHtml).append(">");
        }
    }

    @Override
    public void toTex(StringBuilder sb) {
        sb.append(highlightTexOpen);
        for (Markup item : items) {
            if (item instanceof Text) {
                ((Text) item).toTex(sb);
            } else if (item instanceof AbstractMarkup) {
                ((AbstractMarkup) item).toTex(sb);
            } else if (item instanceof AbstractList) {
                ((AbstractList) item).toTex(sb);
            }
        }
        sb.append(highlightTexClose);
    }
}
