/* InfoFunctionImpl.java

	Purpose:
		
	Description:
		
	History:
		Oct 19, 2010 4:23:06 PM, Created by ashish

Copyright (C) 2010 Potix Corporation. All Rights Reserved.

*/
package org.zkoss.zssex.formula.fn;

import org.zkoss.poi.ss.formula.eval.AreaEval;
import org.zkoss.poi.ss.formula.eval.BoolEval;
import org.zkoss.poi.ss.formula.eval.ErrorEval;
import org.zkoss.poi.ss.formula.eval.EvaluationException;
import org.zkoss.poi.ss.formula.eval.NumberEval;
import org.zkoss.poi.ss.formula.eval.OperandResolver;
import org.zkoss.poi.ss.formula.eval.StringEval;
import org.zkoss.poi.ss.formula.eval.ValueEval;
import org.zkoss.poi.ss.formula.functions.Function;
import org.zkoss.poi.ss.formula.functions.NumericFunction;
import org.zkoss.poi.ss.formula.functions.TextFunction;
import org.zkoss.poi.ss.formula.functions.TextFunctionHelper;


/**
 * @author ashish
 *
 */
public class InfoFunctionImpl {
	
	
	/**
	 * Excel 2007 help document: ISERR(value): Returns TRUE if value refers to any error value except #N/A 
	 */
	public static final Function ISERR = new TextFunction() {
		@Override
		protected ValueEval evaluateFunc(ValueEval[] args, int srcCellRow,
				int srcCellCol) throws EvaluationException {
			//ZSS-266 Info formula "ISERR" is evaluated to a wrong result, hawk
			try{
				ValueEval vEval = OperandResolver.getSingleValue(args[0], srcCellRow, srcCellCol);
				return BoolEval.valueOf( vEval instanceof ErrorEval && vEval != ErrorEval.NA);
			}catch (Exception e) {
				// all exceptions happen during evaluation can be treated as error values 
				return BoolEval.valueOf(true);
			}
		}
	};


	public static final Function N = new TextFunction() {

		@Override
		protected ValueEval evaluateFunc(ValueEval[] args, int srcCellRow,
				int srcCellCol) throws EvaluationException {
			ValueEval ve = OperandResolver.getSingleValue(args[0], srcCellRow, srcCellCol);

			if(ve instanceof NumberEval) {
				return args[0];
			} else if(ve instanceof StringEval){
				return new NumberEval(0);
			} else if (ve instanceof BoolEval) {
				return new NumberEval(((BoolEval)ve).getNumberValue());
			} else {
				return new NumberEval(0);
			}
		}
	};
	
	public static final Function TYPE = new NumericFunction() {

		@Override
		protected double eval(ValueEval[] args, int srcCellRow, int srcCellCol)
				throws EvaluationException {
			ValueEval ve = args[0];
			if(!(ve instanceof ErrorEval)) {
			 ve = OperandResolver.getSingleValue(args[0], srcCellRow, srcCellCol);
			}
			
			if(ve instanceof NumberEval) {
				return 1;
			} else if(ve instanceof StringEval){
				return 2;
			} else if (ve instanceof BoolEval) {
				return 4;
			} else if (ve instanceof ErrorEval) {
				return 16;
			} else if (ve instanceof AreaEval) {
				return 64;
			} else {
				return 0;
			}
		}
	};
}
