package com.atlassian.confluence.extra.livesearch;

import com.atlassian.confluence.renderer.radeox.macros.MacroUtils;
import com.atlassian.confluence.renderer.radeox.macros.AbstractHtmlGeneratingMacro;
import com.atlassian.confluence.renderer.PageContext;
import com.atlassian.confluence.util.VelocityUtils;
import com.atlassian.confluence.spaces.SpaceManager;
import com.atlassian.renderer.v2.RenderUtils;
import com.opensymphony.util.TextUtils;
import org.radeox.macro.parameter.MacroParameter;

import java.io.IOException;
import java.util.Map;

/**
 * This macro defines a live search box.
 * <p>
 * Usage:
 * <pre>
 * {livesearch}
 * </pre>
 */
public class LiveSearchMacro extends AbstractHtmlGeneratingMacro
{
    private SpaceManager spaceManager;

    protected String getHtml(MacroParameter macroParameter) throws IllegalArgumentException, IOException
    {
        try
        {
            PageContext pageContext = (PageContext) macroParameter.getContext().getParameters().get("RENDER_CONTEXT");
            String spaceKey = macroParameter.get("spaceKey");
            // If we are rendering for thr WYSIWYG 'preview' tab, display a message and don't render the macro
            if (PageContext.PREVIEW.equals(pageContext.getOutputType()))
                return RenderUtils.error("The livesearch macro cannot be rendered in 'preview' mode.");

            Map contextMap = MacroUtils.defaultVelocityContext();
            if (TextUtils.stringSet(spaceKey))
            {
                contextMap.put("spaceKey", spaceKey);
                contextMap.put("space", spaceManager.getSpace(spaceKey));
            }
            return VelocityUtils.getRenderedTemplate("templates/extra/livesearch/livesearchmacro.vm", contextMap);
        }
        catch (Exception e)
        {
            log.error("Error while trying to display TaskList!", e);
            throw new IOException(e.getMessage());
        }
    }

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

    public void setSpaceManager(SpaceManager spaceManager)
    {
        this.spaceManager = spaceManager;
    }
}