package com.atlassian.confluence.extra.workflow;

import com.atlassian.confluence.core.ContentEntityObject;
import com.atlassian.confluence.core.ContentPropertyManager;
import com.atlassian.confluence.pages.Page;

/**
 * Created by IntelliJ IDEA.
 * User: Tomd
 * Date: 3/05/2005
 * Time: 17:19:01
 * To change this template use File | Settings | File Templates.
 */
public class ConfluencePageWorkflowClient implements WorkflowClient
{
    private static final String STATE_PROPERTY_KEY = "com.atlassian.workflow.state";
    private static final String TYPE_PROPERTY_KEY = "com.atlassian.workflow.type";
    private ContentEntityObject page;
    private WorkflowType type;
    private ContentPropertyManager contentPropertyManager;

    public ConfluencePageWorkflowClient(ContentEntityObject entity,
                                        WorkflowType type,
                                        ContentPropertyManager contentPropertyManager)
    {
        this.page = entity;
        this.type = type;
        this.contentPropertyManager = contentPropertyManager;
    }

    public ConfluencePageWorkflowClient(ContentEntityObject entity,
                                        ContentPropertyManager contentPropertyManager)
    {
        this.page = entity;
        String typeId = contentPropertyManager.getStringProperty(page, TYPE_PROPERTY_KEY);
        if (typeId == null)
        {
            throw new RuntimeException("Page " + entity.getTitle() + " is not a workflow client.");
        }
        this.type = WorkflowManager.findType(typeId);
        this.contentPropertyManager = contentPropertyManager;
    }

    public State getState()
    {
        String stateId = contentPropertyManager.getStringProperty(page, STATE_PROPERTY_KEY);
        if (stateId == null)
        {
            return type.getStateById("NOT_STARTED");
        }
        else
        {
            return type.getStateById(stateId);
        }
    }

    public void setState(State state)
    {
        contentPropertyManager.setStringProperty(page, STATE_PROPERTY_KEY, state.getId());
        contentPropertyManager.setStringProperty(page, TYPE_PROPERTY_KEY, type.getName());
    }

    public void setValue(String key, String value)
    {
        contentPropertyManager.setStringProperty(page, key, value);
    }

    public String getValue(String key)
    {
        return contentPropertyManager.getStringProperty(page, key);
    }

    public void unsetValue(String key)
    {
        contentPropertyManager.setStringProperty(page, key, null);
    }

    public ContentEntityObject getContentEntityObject()
    {
        return page;
    }

    public static boolean isWorkflowPage(Page page,
                                         ContentPropertyManager contentPropertyManager)
    {
        return contentPropertyManager.getStringProperty(page, TYPE_PROPERTY_KEY) != null;
    }

    public WorkflowType getType()
    {
        return type;
    }
}
