// Upgrade.java
// $Id: Upgrade.java,v 1.4 1997/07/22 12:47:55 abaird Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.jigsaw.upgrade;

import java.util.*;

/**
 * The main, upgrader class.
 */

public class Upgrade {
    /**
     * The known versions.
     */
    private static int versions[] = { 1, 2, 3 };
    /**
     * The corresponding upgraders.
     */
    private static String upgraders[] = {
	null,
	"w3c.jigsaw.upgrade.Upgrade1to2",
	"w3c.jigsaw.upgrade.Upgrade2to3"
    };

    /*
     * Convert given class names to an array of Upgrader.
     */

    private static Upgrader[] toClassArray(Vector apply) {
	Upgrader ret[] = new Upgrader[apply.size()];
	for (int i = 0 ; i < ret.length; i++) {
	    try {
		Class c = Class.forName((String) apply.elementAt(i));
		ret[i]  = (Upgrader) c.newInstance();
	    } catch (Exception ex) {
		ex.printStackTrace();
	    }
	}
	return ret;
    }

    /**
     * Look for an upgrader class to go from one bersion to another.
     * @param from The version that has emitted the current configuration.
     * @param to The version that is trying to read that configuration.
     * @return An array of upgraders, to be applied in the order in which
     * they are returned, or <strong>null</strong> if no upgrade is to be
     * performed.
     */

    public static Upgrader[] getUpgrader(int from, int to) {
	// Fast check:
	if (from >= to)
	    return null;
	// Aggregate upgraders
	Vector apply = null;
	for (int i = 0 ; i < versions.length; i++) {
	    // Any upgrader defined ?
	    if (versions[i] > from) {
		if ( upgraders[i] == null )
		    continue;
		// Init if needed, and mark as needing application:
		if ( apply == null )
		    apply = new Vector();
		apply.addElement(upgraders[i]);
	    } 
	    // Are we done ?
	    if ( versions[i] == to ) 
		return toClassArray(apply);
	}
	return (apply != null) ? toClassArray(apply) : null;
    }

}
