/*
 * Copyright 2020 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kie.pmml.commons.model.predicates;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.BinaryOperator;

import org.kie.pmml.api.enums.BOOLEAN_OPERATOR;
import org.kie.pmml.api.exceptions.KiePMMLException;
import org.kie.pmml.commons.model.KiePMMLExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @see <a href=http://dmg.org/pmml/v4-4/TreeModel.html#xsdElement_SimplePredicate>SimplePredicate</a>
 */
public class KiePMMLCompoundPredicate extends KiePMMLPredicate {

    private static final Logger logger = LoggerFactory.getLogger(KiePMMLCompoundPredicate.class);
    private static final long serialVersionUID = -8106791592643949001L;

    private final BOOLEAN_OPERATOR booleanOperator;
    protected BinaryOperator<Boolean> operatorFunction;
    protected List<KiePMMLPredicate> kiePMMLPredicates;

    protected KiePMMLCompoundPredicate(final String name, final List<KiePMMLExtension> extensions, final BOOLEAN_OPERATOR booleanOperator) {
        super(name, extensions);
        this.booleanOperator = booleanOperator;
    }

    /**
     * Builder to auto-generate the <b>id</b>
     * @return
     */
    public static Builder builder(List<KiePMMLExtension> extensions, BOOLEAN_OPERATOR booleanOperator) {
        return new Builder(extensions, booleanOperator);
    }

    @Override
    public boolean evaluate(Map<String, Object> values) {
        Boolean toReturn = null;
        for (KiePMMLPredicate kiePMMLPredicate : kiePMMLPredicates) {
            Boolean evaluation = kiePMMLPredicate.evaluate(values);
            switch (booleanOperator) {
                case OR:
                    toReturn = orOperator(toReturn, evaluation);
                    break;
                case AND:
                    toReturn = andOperator(toReturn, evaluation);
                    break;
                case XOR:
                    toReturn = xorOperator(toReturn, evaluation);
                    break;
                case SURROGATE:
                    toReturn = surrogateOperator(toReturn, evaluation);
                    break;
                default:
                    throw new KiePMMLException("Unknown BOOLEAN_OPERATOR " + booleanOperator);
            }
        }
        return toReturn != null && toReturn;
    }

    @Override
    public String getId() {
        return id;
    }

    public BOOLEAN_OPERATOR getBooleanOperator() {
        return booleanOperator;
    }

    public List<KiePMMLPredicate> getKiePMMLPredicates() {
        return kiePMMLPredicates;
    }

    @Override
    public String toString() {
        return "KiePMMLCompoundPredicate{" +
                "booleanOperator=" + booleanOperator +
                ", operatorFunction=" + operatorFunction +
                ", kiePMMLPredicates=" + kiePMMLPredicates +
                ", extensions=" + extensions +
                ", id='" + id + '\'' +
                ", parentId='" + parentId + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        if (!super.equals(o)) {
            return false;
        }
        KiePMMLCompoundPredicate that = (KiePMMLCompoundPredicate) o;
        return booleanOperator == that.booleanOperator &&
                Objects.equals(operatorFunction, that.operatorFunction) &&
                Objects.equals(kiePMMLPredicates, that.kiePMMLPredicates);
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), booleanOperator, operatorFunction, kiePMMLPredicates);
    }

    static Boolean orOperator(Boolean aBoolean, Boolean aBoolean2) {
        logger.trace("orOperator {} {}",  aBoolean,  aBoolean2);
        return aBoolean != null ? aBoolean || aBoolean2 : aBoolean2;
    }

    static Boolean andOperator(Boolean aBoolean, Boolean aBoolean2) {
        logger.trace("andOperator {} {}",  aBoolean,  aBoolean2);
        return aBoolean != null ? aBoolean && aBoolean2 : aBoolean2;
    }

    static Boolean xorOperator(Boolean aBoolean, Boolean aBoolean2) {
        logger.trace("xorOperator {} {}",  aBoolean,  aBoolean2);
        return aBoolean != null ? aBoolean ^ aBoolean2 : aBoolean2;
    }

    static Boolean surrogateOperator(Boolean aBoolean, Boolean aBoolean2) {
        logger.trace("surrogateOperator {} {}",  aBoolean,  aBoolean2);
        return aBoolean != null ? aBoolean : aBoolean2;
    }

    public static class Builder extends KiePMMLPredicate.Builder<KiePMMLCompoundPredicate> {

        private Builder(List<KiePMMLExtension> extensions, BOOLEAN_OPERATOR booleanOperator) {
            super("CompoundPredicate-", () -> new KiePMMLCompoundPredicate("CompoundPredicate", extensions, booleanOperator));
            toBuild.operatorFunction = getInnerBinaryOperator(booleanOperator);
        }

        public KiePMMLCompoundPredicate.Builder withKiePMMLPredicates(List<KiePMMLPredicate> kiePMMLPredicates) {
            kiePMMLPredicates.forEach(predicate -> predicate.setParentId(toBuild.id));
            toBuild.kiePMMLPredicates = kiePMMLPredicates;
            return this;
        }

        private BinaryOperator<Boolean> getInnerBinaryOperator(BOOLEAN_OPERATOR booleanOperator) {
            switch (booleanOperator) {
                // logic here is
                // first boolean may be null (initial evaluation) so we start taking the second boolean
                case OR:
                    return KiePMMLCompoundPredicate::orOperator;
                case AND:
                    return KiePMMLCompoundPredicate::andOperator;
                case XOR:
                    return KiePMMLCompoundPredicate::xorOperator;
                case SURROGATE:
                    return KiePMMLCompoundPredicate::surrogateOperator;
                default:
                    throw new KiePMMLException("Unknown BOOLEAN_OPERATOR " + booleanOperator);
            }
        }
    }
}

@@ -1057,22 +1057,24 @@
 Element_
-Simple
+Compound
 Predicat
@@ -1079,14 +1079,16 @@
 ate%3E
-Simple
+Compound
 Pred
@@ -1394,64 +1394,8 @@
 or;%0A
-    protected BinaryOperator%3CBoolean%3E operatorFunction;%0A
     
@@ -3293,67 +3293,8 @@
 r +%0A
-                %22, operatorFunction=%22 + operatorFunction +%0A
     
@@ -3918,83 +3918,8 @@
  &&%0A
-                Objects.equals(operatorFunction, that.operatorFunction) &&%0A
     
@@ -4104,26 +4104,8 @@
 tor,
- operatorFunction,
  kie
@@ -5292,88 +5292,8 @@
 ));%0A
-            toBuild.operatorFunction = getInnerBinaryOperator(booleanOperator);%0A
     
@@ -5599,805 +5599,8 @@
  %7D%0A%0A
-        private BinaryOperator%3CBoolean%3E getInnerBinaryOperator(BOOLEAN_OPERATOR booleanOperator) %7B%0A            switch (booleanOperator) %7B%0A                // logic here is%0A                // first boolean may be null (initial evaluation) so we start taking the second boolean%0A                case OR:%0A                    return KiePMMLCompoundPredicate::orOperator;%0A                case AND:%0A                    return KiePMMLCompoundPredicate::andOperator;%0A                case XOR:%0A                    return KiePMMLCompoundPredicate::xorOperator;%0A                case SURROGATE:%0A                    return KiePMMLCompoundPredicate::surrogateOperator;%0A                default:%0A                    throw new KiePMMLException(%22Unknown BOOLEAN_OPERATOR %22 + booleanOperator);%0A            %7D%0A        %7D%0A
     

Fix serialization issue on KiePMMLCompoundPredicate (#3850)