package org.wso2.siddhi.extension;

import java.lang.Math;

import org.apache.log4j.Logger;
import org.wso2.siddhi.core.config.SiddhiContext;
import org.wso2.siddhi.core.exception.QueryCreationException;
import org.wso2.siddhi.core.executor.function.FunctionExecutor;
import org.wso2.siddhi.query.api.definition.Attribute;
import org.wso2.siddhi.query.api.definition.Attribute.Type;
import org.wso2.siddhi.query.api.extension.annotation.SiddhiExtension;

@SiddhiExtension(namespace = "custom", function = "abs")
public class AbsExtension extends FunctionExecutor {
	Logger log = Logger.getLogger(AbsExtension.class);
	Attribute.Type returnType;

	/**
	 * Method will be called when initialising the custom function
	 * 
	 * @param types
	 * @param siddhiContext
	 */
	@Override
	public void init(Attribute.Type[] types, SiddhiContext siddhiContext) {
		if (types.length != 1) {
			throw new QueryCreationException("Invalid no of Arguments Passed.");
		}
		for (Attribute.Type attributeType : types) {
			if ((attributeType == Attribute.Type.DOUBLE)||(attributeType == Attribute.Type.INT)||(attributeType == Attribute.Type.FLOAT)||(attributeType == Attribute.Type.LONG)) {
				returnType = Type.DOUBLE;
				break;
			} else {
				throw new QueryCreationException("Invalid parameters type - "
						+ attributeType.toString());
			}
		}
	}

	/**
	 * Method called when sending events to process
	 * 
	 * @param obj
	 * @return
	 */
	@Override
	protected Object process(Object obj) {
		try {
			if (returnType == Attribute.Type.DOUBLE) {
				double returnValue = 0;
				if (obj != null) {
					returnValue = Math.abs(Double.parseDouble(String
							.valueOf(obj))); 
				}
				return returnValue;
			} else {
				return 0;
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return 0;

		}
	}

	@Override
	public void destroy() {
	}

	/**
	 * Return type of the custom function mentioned
	 * 
	 * @return
	 */

	@Override
	public Attribute.Type getReturnType() {
		return returnType;
	}

}