package com.atlassian.confluence.extra.workflow;

import com.atlassian.confluence.core.ContentEntityObject;
import com.atlassian.confluence.core.ContentPropertyManager;
import com.atlassian.confluence.pages.PageManager;
import com.atlassian.confluence.renderer.PageContext;
import com.atlassian.confluence.renderer.radeox.macros.MacroUtils;
import com.atlassian.confluence.user.AuthenticatedUserThreadLocal;
import com.atlassian.confluence.util.VelocityUtils;
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.user.User;
import org.apache.log4j.Category;

import java.util.Map;


/**
 * Created by IntelliJ IDEA.
 * User: Tomd
 * Date: 3/05/2005
 * Time: 10:07:22
 * To change this template use File | Settings | File Templates.
 */
public class WorkflowTypeMacro extends BaseMacro
{
    protected static final Category log = Category.getInstance(WorkflowTypeMacro.class);
    private ContentPropertyManager contentPropertyManager;
    public void setPageManager(PageManager pageManager)
    {
        this.pageManager = pageManager;
    }

    private PageManager pageManager;

    public boolean isInline()
    {
        return false;
    }

    public boolean hasBody()
    {
        return false;
    }

    // irrelevant since we have no body
    public RenderMode getBodyRenderMode()
    {
        return RenderMode.NO_RENDER;
    }

    public String execute(Map parameters, String body, RenderContext renderContext) throws MacroException
    {
        User user = AuthenticatedUserThreadLocal.getUser();
        PageContext pageContext = (PageContext)renderContext;

        String workflowType = (String)parameters.get("0");

        if (workflowType == null)
        {
            throw new MacroException("No workflow type name specified. usage {workflowtype:<i>typeName</i>}");
        }
        WorkflowType t = WorkflowManager.findType(workflowType);
        if (t == null)
        {
            throw new MacroException("The workflow type '" + workflowType + "' is unknown.");
        }


        Map contextMap = MacroUtils.defaultVelocityContext();
        contextMap.put("type", t);
        ContentEntityObject contentObject = ((PageContext)renderContext).getEntity();
        contextMap.put("content", contentObject);
        contextMap.put("edit", Boolean.TRUE);
        contextMap.put("page",contentObject);
        try
        {
            return VelocityUtils.getRenderedTemplate("templates/extra/workflow/workflowtypemacro.vm", contextMap);
        }
        catch (Exception e)
        {
            log.error("Error while trying to display Macro!", e);
            throw new MacroException(e.getMessage(),e);
        }
    }

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