package com.atlassian.confluence.extra.dynamictasklist;

import com.atlassian.confluence.core.ContentPropertyManager;
import com.atlassian.confluence.core.ContentEntityObject;
import com.atlassian.confluence.extra.dynamictasklist.model.TaskList;
import com.atlassian.renderer.v2.SubRenderer;
import com.thoughtworks.xstream.XStream;

public class TaskListManager
{
    ContentPropertyManager contentPropertyManager;
    XStream xStream;
    SubRenderer subRenderer;

    public TaskList getTaskList(ContentEntityObject contentObject, String listName)
    {
        ClassLoader callersLoader = Thread.currentThread().getContextClassLoader();
        try
        {
            // TEMPORARY HACK: until we work out a way to make the plugin class loaders available to the system correctly.
            // Ensure that this classes class loader is being used when we run xstream. If this plugin is uploaded to confluence,
            // then only this classes loader will have access to all of the other classes deployed with this plugin.
            Thread.currentThread().setContextClassLoader(getClass().getClassLoader());

            String listAsXml = contentPropertyManager.getTextProperty(contentObject, createKey(listName));

            if (listAsXml == null)
            {
                return new TaskList(listName);
            }
            else
            {
                return (TaskList) xStream.fromXML(listAsXml);
            }
        }
        finally
        {
            // return things to as they were before we started messing about with the classloader.
            Thread.currentThread().setContextClassLoader(callersLoader);
        }
    }

    private String createKey(String listName)
    {
        return "atlassian.dynamictasklist:" + listName.substring(0, Math.min(listName.length() - 1, 100));
    }

    public void setxStream(XStream xStream)
    {
        this.xStream = xStream;
    }

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

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

    public void saveTaskList(ContentEntityObject contentObject, TaskList list)
    {
        contentPropertyManager.setTextProperty(contentObject, createKey(list.getName()), xStream.toXML(list));
    }
}
