package org.apache.slide.projector.processor;

import java.util.Map;

import org.apache.commons.contract.Context;
import org.apache.commons.contract.Processor;
import org.apache.commons.contract.Result;
import org.apache.commons.contract.constraints.NumberConstraints;
import org.apache.commons.contract.descriptor.ParameterDescriptor;
import org.apache.commons.contract.descriptor.ResultDescriptor;
import org.apache.commons.contract.descriptor.ResultEntryDescriptor;
import org.apache.commons.contract.descriptor.StateDescriptor;
import org.apache.commons.contract.i18n.ParameterMessage;
import org.apache.commons.i18n.LocalizedMessage;

public class Calculator implements Processor {
    private final static String FIRST_NUMBER = "firstNumber";
    private final static String SECOND_NUMBER = "secondNumber";
    private final static String CALCULATED_RESULT = "calculatedResult";

    private final static ParameterDescriptor[] parameterDescriptors = new ParameterDescriptor[]{new ParameterDescriptor(
            FIRST_NUMBER, new ParameterMessage(
                    "calculator/parameter/firstNumber"),
            new NumberConstraints(new Integer(0), new Integer(5)))};
    private final static ResultDescriptor[] resultDescriptors = new ResultDescriptor[]{
            new ResultDescriptor(
            new StateDescriptor(StateDescriptor.OK, new LocalizedMessage("calculator/state/ok")),
            new ResultEntryDescriptor[]{new ResultEntryDescriptor(
                    CALCULATED_RESULT, new LocalizedMessage("calculator/result/calculatedResult"),
                    NumberConstraints.UNCONSTRAINED)})
    };

    public Result process(Map parameter, Context context) throws Exception {
        int firstInt = ((Number)parameter.get(FIRST_NUMBER))
                .intValue();
        int secondInt = ((Number) parameter.get(SECOND_NUMBER))
                .intValue();
        int calculatedResult = firstInt + secondInt;
        return new Result(StateDescriptor.OK, CALCULATED_RESULT,
                new Integer(calculatedResult));
    }

    public ParameterDescriptor[] getParameterDescriptors() {
        return parameterDescriptors;
    }

    public ResultDescriptor[] getResultDescriptors() {
        return resultDescriptors;
    }
}