/*  
 * Copyright 2004-2009 unitarou <boss@unitarou.org>. 
 * All rights reserved.
 * 
 * This program and the accompanying materials are made available under the terms of 
 * the Common Public License v1.0 which accompanies this distribution, 
 * and is available at http://opensource.org/licenses/cpl.php
 * 
 * Contributors:
 *     unitarou - initial API and implementation
 */
package org.unitarou.yukinoshita.model.cmd;

import org.unitarou.lang.ArgumentChecker;
import org.unitarou.lang.Strings;
import org.unitarou.sgf.CardinalityType;
import org.unitarou.sgf.Property;
import org.unitarou.sgf.SgfId;
import org.unitarou.yukinoshita.model.NodeView;

/**
 * @author unitarou &lt;boss@unitarou.org&gt; 
 */
public class CommandFactory {

    /**
     * {@link UpdateProperty}ðì¬µÄÔµÜ·B<br>
     * ±±ÅnewDatumªóÌêÍnodeView©çsgfTypeðí·éR}hÉÈèÜ·B<br>
     * Ü½nodeViewÌlÆnewDatumÉ·ª³¢êÍnullðÔµÜ·B
     *  
     * @param newDatum {@link Property#Property(SgfId, String)}É¼Ún³êé¶ñAó¶ÌêÍíðÓ¡µÜ·B
     *                  <b>GXP[vÍÖ~Å·B</b>
     * @param sgfId XVÎÛÆÈévpeBÌ^
     * @param nodeView 
     * @param bindSameType trueÉÝè·éÆ{@link SgfId#propertyType()}ðÂNodeÜÅkÁÄA
     *                      (øÌnodeViewÅÍÈ­)»Ìm[hðXVµÜ·B
     * @return ì¬³ê½vpeBBNOT NULL
     * @throws org.unitarou.lang.NullArgumentException øª<code>null</code>ÌêB
     * @throws IllegalArgumentException sgfType ª{@link CardinalityType#SINGLE}ÈOÌlðÂB
     */
    static public UpdateProperty createUpdateProperty(
    		String newDatum, SgfId sgfId, NodeView nodeView, boolean bindSameType) 
    {
    	ArgumentChecker.throwIfNull(newDatum, sgfId, nodeView);
    	if (!sgfId.cardinalityType().equals(CardinalityType.SINGLE)) {
    		throw new IllegalArgumentException("Bad carinality, property must be single: " + sgfId); //$NON-NLS-1$
    	}
    	
        Property property = bindSameType 
        		? nodeView.findProperty(sgfId) 
        		: nodeView.getProperty(sgfId);
        String lastDatum = Strings.EMPTY;
        if (property != null) {
            lastDatum = property.getString();
        }
        if (newDatum.equals(lastDatum)) {
            return null;
        }
        if (newDatum.equals(Strings.EMPTY)) { // í
            // øÅGameInfoª éã¬ÌNodeÉXV·éæ¤Éwè
            property = new Property(sgfId, lastDatum);
            return new UpdateProperty(
            			(bindSameType) ? sgfId.propertyType() : null, 
            			null, 
            			property);
        }
        // øÅGameInfoª éã¬ÌNodeÉXV·éæ¤Éwè
        property = new Property(sgfId, newDatum);
        return new UpdateProperty(
        			(bindSameType) ? sgfId.propertyType() : null, 
        			property);
    }

    /**
	 * 
	 */
	protected CommandFactory() {
		super();
	}

}
