package org.jcon.param.util;

import org.jcon.param.Param;
import org.jcon.param.ParamConverter;
import org.jcon.util.DataLib;
import java.util.Vector;

/**
 * This class replaces items in a Param, allowing dynamic
 * system behavior and greater Param reuse.
 *
 * @author Jack Harich
 */
public class ParamReplacer {
    
//---------- Private Fields ------------------------------
private Vector items = new Vector();
        
//---------- Public Methods ------------------------------
/**
* Adds the text pair. When apply() is called all occurances
* of oldText will be replaced with the newText.
*/
public void add(String oldText, String newText) {
    items.addElement(new Item(oldText, newText));
}
/**
* Applies any items to the oldParam and returns the modified
* Param. If there is nothing to apply then the oldParam is
* returned.
*/
public Param apply(Param oldParam) {
    if (items.isEmpty()) return oldParam;
    
    // Get modified text, consider full text possibility
    String text;    
    if (oldParam.hasFullText()) {
        text = oldParam.getFullText();
    } else {
        text = oldParam.getText();
    }
    for (int i = items.size(); --i >= 0;) {
        Item item = (Item)items.elementAt(i);
        text = replace(text, item);
    }
    // Rebuild param
    if (oldParam.hasFullText()) {
        // Args are fullText, original text
        return ParamConverter.toParam(text, oldParam.getText());
    } else {
        return ParamConverter.toParam(text);
    }
}    
//---------- Private Methods -----------------------------
private String replace(String text, Item item) {
    while (text.indexOf(item.oldText) >= 0) {
        text = DataLib.replaceToken(text, item.oldText, item.newText);   
    }
    return text; 
}  
//========== Inner Classes ===============================
private class Item {
    String oldText;
    String newText;
    
    Item(String oldText, String newText) {
        this.oldText = oldText;
        this.newText = newText;   
    }
    
} // End inner class    
    
} // End outer class
