package aee.csv;

import aee.engine.Rule;
import aee.engine.RuleTable;
import aee.exception.AeeException;
import aee.util.StringUtils;

/**
 * Write flow rules as a CSV file
 */
public class FlowRulesCsvWriter extends CsvWriter {

	/**
	 * Constructor
	 * @param fn Filename to write
	 * @throws AeeException if any I/O exception
 	 */
	public FlowRulesCsvWriter(String fn) throws AeeException {
		super(fn);
	}
	
	/**
	 * Write the flow rules to the file
	 * @param table The flow rules
	 * @throws AeeException if any I/O exception
	 */
	public void write(RuleTable table) throws AeeException {
		
		// The header also defines the number of columns in each record
		String[] record = new String[]{"Rule #","Active","Type","",
				                           "","","","","","","","Comments"};
		write(record);
		
		for (Rule rule : table.getRules()) {
			record[0] = String.format("%d", rule.getId());
			record[1] = rule.isActive()? "Y" : "N";
			record[2] = rule.getRuleCategory();
			record[3] = rule.getOperation().getResultString();
			record[4] = rule.getOperation().getType().toExternalString();
			
			// The terms
			final int TermBeg = 5;
			final int TermEnd = 10;
			for (int i = TermBeg; i < TermEnd; i++)
				record[i] = "";
			
			String[] terms = rule.getOperation().getExternalTerms();
			if (terms.length > TermEnd-TermBeg)
				throw new AeeException("Invalid operation: \"%s\" required too many Excel columns",
						                   StringUtils.join(terms, " "));
			System.arraycopy(terms, 0, record, TermBeg, terms.length);
			
			record[10] = "";
			record[11] = rule.getComment();
			write(record);
		}
	}
}
