package com.sinosig.util.valuerule.condition;

import lombok.Data;
import com.sinosig.util.valuerule.VRCondition;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Data
public class VRGroupCondition<T> extends VRCondition<T> {

    //是否为与逻辑
    private Boolean isAndLogic;
    //子条件集合
    private List<VRCondition> vrConditions;

    public VRGroupCondition(String name, Boolean isNotMode, String ruleInfo, T value) {
        super(name, isNotMode, ruleInfo, value);
        vrConditions = new ArrayList<>();
    }

    public VRGroupCondition<T> init(Boolean isAndLogic) {
        this.isAndLogic = isAndLogic;
        return this;
    }

    public VRGroupCondition<T> add(VRCondition<T> vrCondition) {
        vrConditions.add(vrCondition);
        return this;
    }

    @Override
    public boolean validate() {
        if (CollectionUtils.isEmpty(vrConditions)) {
            return true;
        }

        if (isAndLogic) {
            return andConditions();
        } else {
            return orConditions();
        }

    }

    public boolean andConditions() {
        boolean isValid = vrConditions.get(0).isValid();
        for (int i = 1; i < vrConditions.size(); i++) {
            isValid = isValid && vrConditions.get(i).isValid();

            if (isValid == false) {
                return false;
            }
        }
        return isValid;
    }

    public boolean orConditions() {
        boolean isValid = vrConditions.get(0).isValid();
        for (int i = 1; i < vrConditions.size(); i++) {
            isValid = isValid || vrConditions.get(i).isValid();

            if (isValid == true) {
                return true;
            }
        }
        return isValid;
    }
}
