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 com.opensymphony.util.TextUtils;
import org.w3c.dom.Node;

import java.util.Map;

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

    public boolean suppressSurroundingTagDuringWysiwygRendering()
    {
        return true;
    }

    public boolean suppressMacroRenderingDuringWysiwyg()
    {
        return true;
    }

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

    public boolean isInline()
    {
        return false;
    }

    public boolean hasBody()
    {
        return true;
    }

    public RenderMode getBodyRenderMode()
    {
        return RenderMode.ALL;
    }

    public String execute(Map parameters, String body, RenderContext renderContext) throws MacroException
    {
        String width = null;

        if (TextUtils.stringSet((String) parameters.get("width")))
        {
            width = (String) parameters.get("width");
            if(!width.endsWith("%"))
            {
                width += "%";
            }
        }
        
        String wysiwyg = "";
        String wysiwygInfo = "";
        if (renderContext.isRenderingForWysiwyg())
        {
            wysiwyg = "wysiwyg=\"macro:" + getName() + "\"";
            //wysiwygInfo = wysiwygConverter.getMacroInfoHtml(renderContext, getName(), 32, 0);
        }
        return "<td class=\"confluenceTd\" " + wysiwyg + " valign=\"top\"" +
                (width != null ? " width=\"" + width + "\"" : "") +
                ">" + wysiwygInfo + 
                body + "</td>";
    }

    public String convertXHtmlToWikiMarkup(Node previousSibling, Node node, WysiwygConverter helper, Styles styles, ListContext listContext, boolean inTable, boolean inListItem, boolean ignoreText)
    {
        String width = "";
        if (helper.getAttribute(node, "width") != null)
        {
            width = ":width=" + helper.getAttribute(node, "width");
        }
        boolean escapeWikiMarkup = true;
        return wysiwygConverter.getSep(previousSibling, "div", inTable, inListItem) + "\n{column" + width + "}\n" + helper.convertChildren(node, styles, listContext, inTable, inListItem, ignoreText, escapeWikiMarkup, null) + "\n{column}";
    }

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