package com.atlassian.confluence.extra.masterdetail;

import com.atlassian.renderer.v2.macro.BaseMacro;
import com.atlassian.renderer.v2.RenderMode;
import com.atlassian.renderer.v2.SubRenderer;
import com.atlassian.renderer.RenderContext;
import com.atlassian.confluence.util.GeneralUtil;
import com.atlassian.confluence.core.ContentPropertyManager;
import com.atlassian.confluence.labels.LabelManager;
import com.opensymphony.util.TextUtils;

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

import bucket.util.PairType;

public abstract class AbstractMasterDetailsMacro extends BaseMacro
{
    private SubRenderer subRenderer;
    protected ContentPropertyManager contentPropertyManager;
    protected LabelManager labelManager;

    protected String renderErrorBody(String body, RenderContext renderContext)
    {
        return subRenderer.render(body, renderContext);
    }

    protected List toDetails(String body, RenderContext renderContext)
    {
        if (!TextUtils.stringSet(body))
            return Collections.EMPTY_LIST;

        List details = new ArrayList();
        Pattern pat = Pattern.compile("^(.+?):(.+?)$", Pattern.MULTILINE);
        Matcher matcher = pat.matcher(body);
        while (matcher.find())
        {
            details.add(new PairType(GeneralUtil.escapeXml(matcher.group(1).trim()),
                    subRenderer.render(matcher.group(2).trim(), renderContext, renderContext.getRenderMode().and(RenderMode.INLINE))));
        }
        return details;
    }

    public void setSubRenderer(SubRenderer subRenderer)
    {
        this.subRenderer = subRenderer;
    }

    public void setContentPropertyManager(ContentPropertyManager contentPropertyManager)
    {
        this.contentPropertyManager = contentPropertyManager;
    }

    public void setLabelManager(LabelManager labelManager)
    {
        this.labelManager = labelManager;
    }
}
