package org.hisp.dhis.rules.functions;


import org.hisp.dhis.rules.RuleVariableValue;

import java.util.List;
import java.util.Map;

import javax.annotation.Nonnull;

public class RuleFunctionCount extends RuleFunction {
    static final String D2_COUNT = "d2:count";

    @Nonnull
    public static RuleFunctionCount create() {
        return new RuleFunctionCount();
    }

    @Nonnull
    @Override
    public String evaluate(@Nonnull List<String> arguments,
            Map<String, RuleVariableValue> valueMap) {
        if (arguments.size() != 1) {
            throw new IllegalArgumentException("Two arguments were expected, " +
                    arguments.size() + " were supplied");
        }

        return String.valueOf(count(arguments.get(0), valueMap));
    }

    /**
     * Function which will return the number of values for given variableName
     *
     * @param variableName variable name.
     * @param valueMap list of variables.
     * @return return the count the number of values that is entered for the source field in the argument.
     */
    private Integer count(String variableName, Map<String, RuleVariableValue> valueMap) {
        RuleVariableValue ruleVariableValue =valueMap.get(variableName);
        Integer count = 0;
        if(ruleVariableValue != null) {
            if(ruleVariableValue.value()!=null) {
                if(ruleVariableValue.candidates() != null) {
                    count = ruleVariableValue.candidates().size();
                } else {
                    //If there is a value found for the variable, the count is 1 even if there is no list of alternate values
                    //This happens for variables of "DATAELEMENT_CURRENT_STAGE" and "TEI_ATTRIBUTE"
                    count = 1;
                }
            }
        }
        return count;
    }

}

@@ -601,11 +601,11 @@
 on(%22
-Two
+One
  arg
@@ -613,14 +613,12 @@
 ment
-s
  w
-ere
+as
  exp

fix comment