package org.jcon.df.column;

import org.jcon.param.Param;
import java.util.Vector;
import java.util.StringTokenizer;

/**
 * A String code of two or more valid values, such as
 * "M" and "F". A code may NOT include spaces or commas.
 *
 * This class represents an empty value as "".
 *
 * @author Jack Harich
 */

public class CodeColumn extends ColumnDef {

//---------- Private Fields ------------------------------
private Vector validCodes = new Vector();
private String delimCodes; // Comma delimited codes

//---------- Initialization ------------------------------
/**
 * No-arg to allow serialization.
 */
public CodeColumn() {
    super();
    setDefaultValue("");
    type = "Code";
}
/**
 * A convienence constructor. "codes" is a comma
 * delimited list of valid codes. Also sets default to "".
 * Note that spaces are allowed after commas for readibility.
 * Example: new StringColumn("Sex", "M, F");
 */
public CodeColumn(String name, String delimCodes) {
    this();
    setName(name);
    this.delimCodes = delimCodes;
    addCodes();
}
//---------- Abstract Implementation ---------------------
public void initFromParam(Param param) {
    checkStandardProperties(param); // superclass
    delimCodes = param.getString("Codes"); // Required
    addCodes();
}
/**
 * Checks that the value entered is a valid code. Returns
 * null if okay or a message explaining the problem.
 */
public String validateString(String text) {
    for (int i = 0; i < validCodes.size(); i++) {
        String code = (String)validCodes.elementAt(i);
        if (text.equals(code)) return null; // Found
    }
    return displayName + " must be one of these codes:\n"
        + delimCodes;
}
public String getMyPropertySummary() {
    return "Values=" + delimCodes + ",";
}
//---------- Superclass Overrides ------------------------
// Return the max length of my codes
public int getPreferredLength() {
    int max = 0;
    for (int i = 0; i < validCodes.size(); i++) {
        String code = (String)validCodes.elementAt(i);
        if (code.length() > max) max = code.length();
    }
    return max;
}
protected String getAutomaticDescription() {
    if (delimCodes == null) {
        return null;
    } else {
        return "Valid codes are " + delimCodes;
    }
}
//---------- Private Methods -----------------------------
private void addCodes() {
    StringTokenizer tokens = new StringTokenizer(delimCodes, ", ");
    while (tokens.hasMoreElements()) {
        String code = tokens.nextToken();
        validCodes.addElement(code);
    }
}
//--- Std
private void print(String text) {
    System.out.println(text);
}

} // End class
