/*
 *  @(#)AbstractEditableIssue.java
 *
 * Copyright (C) 2002-2003 Matt Albrecht
 * groboclown@users.sourceforge.net
 * http://groboutils.sourceforge.net
 *
 *  Part of the GroboUtils package at:
 *  http://groboutils.sourceforge.net
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the 
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software. 
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 *  DEALINGS IN THE SOFTWARE.
 */
package net.sourceforge.groboutils.pmti.v1.defimpl;

import net.sourceforge.groboutils.pmti.v1.IIssue;
import net.sourceforge.groboutils.pmti.v1.IIssueState;
import net.sourceforge.groboutils.pmti.v1.IAttributeSet;
import net.sourceforge.groboutils.pmti.v1.IEditableIssue;
import net.sourceforge.groboutils.pmti.v1.IEditableIssueState;
import net.sourceforge.groboutils.pmti.v1.IEditableAttributeSet;
import net.sourceforge.groboutils.pmti.v1.ProblemManagerException;


/**
 * Allows for editing of an issue.  The only parts that can't be edited are
 * the ID and type, since those uniquely identify the issue at hand.  Editing
 * an issue has several constraints that should be known by the user:
 *  <UL>
 *      <LI>
 *      Just like with the <tt>IIssue</tt> instances, the issue being
 *      edited will NOT be real-time updated to reflect the current
 *      tracker state.  Currently, the only way to update an issue is by
 *      re-polling the <tt>ProblemManager</tt>.  Individual implementations
 *      may provide for alternative means to receive synchronized issues.
 *      </LI>
 *      <LI>
 *      No changes to an editable issue will be committed to the problem
 *      tracker is to call <tt>commit()</tt> on the issue.
 *      </LI>
 *  </UL>
 *
 * @author     Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @version    $Date: 2003/02/10 22:51:57 $
 * @since      July 12, 2002
 */
public abstract class AbstractEditableIssue implements IEditableIssue
{
    private IIssue baseIssue;
    
    private String newDesc;
    private boolean changedDesc;
    
    private IIssueState newState;
    private boolean changedState;
    
    private IEditableAttributeSet nextSet;
    
    
    
    public AbstractEditableIssue( IIssue base )
    {
        if (base == null)
        {
            throw new IllegalArgumentException("no null arguments");
        }
        this.baseIssue = base;
    }

    
    //-------------------------------------------------------------------------
    // IIssue
    
    
    public String getID()
    {
        return this.baseIssue.getID();
    }
    
    
    public String getType()
    {
        return this.baseIssue.getType();
    }
    
    
    public String getShortDescription()
    {
        if (this.changedDesc)
        {
            return this.newDesc;
        }
        else
        {
            return this.baseIssue.getShortDescription();
        }
    }
    
    
    public IIssueState getState()
    {
        if (this.changedState)
        {
            return this.newState;
        }
        else
        {
            return this.baseIssue.getState();
        }
    }
    
    
    public IAttributeSet getAttributes()
    {
        return getEditableAttributes();
    }
    
    
    public abstract IIssue reload()
            throws ProblemManagerException;

    
    //-------------------------------------------------------------------------
    // IEditableIssue
    
    
    /**
     * 
     */
    public void setShortDescription( String desc )
    {
        String orig = this.baseIssue.getShortDescription();
        if ( desc == orig || ( desc != null && desc.equals( orig ) ) )
        {
            // they're the same - ensure the state is correct
            this.changedDesc = false;
        }
        else
        {
            // changed
            this.changedDesc = true;
            this.newDesc = desc;
        }
    }
    
    
    
    
    /**
     * @return <tt>true</tt> if <tt>setShortDescription( String )</tt> was
     *      called with a different description string than the original
     *      issue, otherwise <tt>false</tt>.
     */
    public boolean hasShortDescriptionChanged()
    {
        return this.changedDesc;
    }
    
    
    /**
     * Returns the list of all states that this issue can move to next.
     * This is part of the workflow logic of the underlying PMT.  The returned
     * states may be safely edited without any affect; the only effect will be
     * when the state is explicitly set.  This will always return, in index 0,
     * a <b>copy</b> of the current state as editable.
     */
    public IEditableIssueState[] getNextStates()
    {
        return createNextEditableIssueStates( getState() );
    }
    
    
    /**
     * Sets the current state.  Since there is no getEditableState() method,
     * use this method if any information in the current state needs to be
     * updated.  You can retrieve the current state as an editable state
     * using <tt>getNextStates()[0]</tt>, but note that any changes to that
     * editable version will not affect the tracker's state unless that
     * editable instance is explicitly set in this method.
     *
     * @exception ProblemManagerException if the input state is not a valid
     *      next state.
     */
    public void setState( IIssueState state )
            throws ProblemManagerException
    {
        assertStateCanBeNext( state );
        
        if (state instanceof IEditableIssueState)
        {
            state = createImmutableIssueState( (IEditableIssueState)state );
        }
        this.newState = state;
        this.changedState = true;
    }
    
    
    /**
     * @return <tt>true</tt> if the <tt>setState( IIssueState )</tt> method
     *      has been invoked and did not throw an exception, otherwise
     *      <tt>false</tt>.  Note that even if the set state is an unchanged
     *      version of the current issue's state, this will still return
     *      <tt>true</tt>.
     */
    public boolean hasStateChanged()
    {
        return this.changedState;
    }
    
    
    /**
     * This is a synonymn for <tt>getAttributes()</tt>, but this explicitly
     * sets the returned value as an editable set, without the need for an
     * extra cast.  The returned attribute set may be safely edited, and
     * changes there will affect the issue that returned them.
     */
    public IEditableAttributeSet getEditableAttributes()
    {
        if (this.nextSet == null)
        {
            // create the editable set
            IAttributeSet s = this.baseIssue.getAttributes();
            this.nextSet = createEditableAttributeSet( s );
        }
        return this.nextSet;
    }
    
    
    /**
     * Commits all changes from the issue to the tracker.
     * <P>
     * In theory, issues should never be removed.  However, some systems allow
     * them to be deleted (say, if there was an accidental creation).  In this
     * case, an <tt>IssueRemovedException</tt> will be thrown.
     *
     * @exception ProblemManagerException if there was an underlying tracker
     *      error.
     */
    public abstract void commit()
            throws ProblemManagerException;
            

    
    //-------------------------------------------------------------------------
    // protected methods
    
    
    /**
     * Creates a set of editable issue states that can be set as 'next' for
     * <tt>is</tt>.  Note that it is required that the input <tt>is</tt>
     * <i>must</i> be returned in index 0 of the returned array.
     */
    protected abstract IEditableIssueState[] createNextEditableIssueStates(
            IIssueState is );
    
    
    /**
     * Creates an editable set of attributes based on the immutable attribute
     * set.  The new set of attributes should accurately reflect the input
     * attribute set's values.
     */
    protected abstract IEditableAttributeSet createEditableAttributeSet(
            IAttributeSet as );
    
    
    /**
     * Create a non-editable version of <tt>eis</tt>.
     */
    protected abstract IIssueState createImmutableIssueState(
            IEditableIssueState eis );
    
    
    
    protected void assertStateCanBeNext( IIssueState state )
            throws ProblemManagerException
    {
        IEditableIssueState[] eis = getNextStates();
        if (eis == null || eis.length < 1)
        {
            throw new IllegalStateException("Invalid set of next states.");
        }
        
        String name = null;
        if (state != null)
        {
            name = state.getName();
        }
        
        for (int i = 0; i < eis.length; ++i)
        {
            if (eis[i] == null)
            {
                if (state == null)
                {
                    // they are the same - null state supported.
                    return;
                }
            }
            else
            // allow for a null name for the input state,
            // but the non-null state must have a non-null name.
            if (eis[i].getName().equals( name ))
            {
                // found the requested state in the next state list,
                // so the requested state is valid.
                return;
            }
        }
        // never found the requested state in the next state list.
        throw new ProblemManagerException( "State "+state+
            " cannot be a next state for "+getState() );
    }
}

