package com.atlassian.confluence.extra.layout;

import com.atlassian.renderer.RenderContext;
import com.atlassian.renderer.v2.RenderMode;
import com.atlassian.renderer.v2.macro.BaseMacro;
import com.atlassian.renderer.v2.macro.MacroException;
import com.atlassian.renderer.wysiwyg.*;
import org.w3c.dom.Node;

import java.util.Map;

public class SectionMacro extends BaseMacro implements WysiwygNodeConverter
{
    private WysiwygConverter wysiwygConverter;

    public boolean suppressSurroundingTagDuringWysiwygRendering()
     {
         return true;
     }
    
    public boolean suppressMacroRenderingDuringWysiwyg()
    {
        return true;
    }

    public String getName()
    {
        return "section";
    }

    public boolean isInline()
    {
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public boolean hasBody()
    {
        return true;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public RenderMode getBodyRenderMode()
    {
        return RenderMode.ALL;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public String execute(Map parameters, String body, RenderContext renderContext) throws MacroException
    {
        String cssClass = " class=\"sectionMacro\"";

        if ("true".equals(parameters.get("border")))
            cssClass = " class=\"sectionMacroWithBorder\"";

        String wysiwyg = "";
        String wysiwygInfo = "";
        if (renderContext.isRenderingForWysiwyg())
        {
            wysiwyg = " wysiwyg=\"macro:" + getName() + "\"";
            //wysiwygInfo = wysiwygConverter.getMacroInfoHtml(renderContext, getName(), 0, 0);
        }
        return "<table" + cssClass + wysiwyg + " border=\"0\" cellpadding=\"5\" cellspacing=\"0\" width=\"100%\">" + wysiwygInfo + "<tbody><tr" + wysiwyg + ">" + body + "</tr></tbody></table>";
    }

    public String convertXHtmlToWikiMarkup(Node previousSibling, Node node, WysiwygConverter helper, Styles styles, ListContext listContext, boolean inTable, boolean inListItem, boolean ignoreText)
    {
        boolean escapeWikiMarkup = true;
        if (node.getNodeName().toLowerCase().equals("table"))
        {
            return wysiwygConverter.getSep(previousSibling, "div", inTable, inListItem) + "\n{section}\n" + helper.convertChildren(node, styles, listContext, inTable, inListItem, ignoreText, escapeWikiMarkup, null) + "\n{section}";
        }
        else if (node.getNodeName().toLowerCase().equals("tr"))
        {
            return helper.convertChildren(node, styles, listContext, inTable, inListItem, ignoreText, escapeWikiMarkup, null);
        }
        else
        {
            throw new RuntimeException("unexpected handler called for tag '" + node.getNodeName() + "'");
        }
    }

    public void setWysiwygConverter(WysiwygConverter wysiwygConverter)
    {
        this.wysiwygConverter = wysiwygConverter;
    }
}
