package games.colonier.ld44.chemistry.rule;

import games.colonier.ld44.chemistry.Molecule;
import games.colonier.ld44.chemistry.MoleculeRule;

import java.util.Arrays;
import java.util.List;

public class CompoundMolecularRule implements MoleculeRule {

    public final List<MoleculeRule> rules;
    public final Operator operator;

    public CompoundMolecularRule (
            List<MoleculeRule> rules,
            Operator operator
    ) {
        this.rules = rules;
        this.operator = operator;
    }

    public CompoundMolecularRule (
            Operator operator,
            MoleculeRule... args
    ) {
        this.operator = operator;
        this.rules = Arrays.asList (args);
    }

    @Override
    public boolean appliesTo (Molecule molecule) {

        switch (operator) {

            case And:

                for (MoleculeRule mr : rules) {
                    if (!mr.appliesTo (molecule)) {
                        return false;
                    }
                }
                return true;

            case Or:

                for (MoleculeRule mr : rules) {
                    if (mr.appliesTo (molecule)) {
                        return true;
                    }
                }
                return true;

            case Not:

                return !rules.get (0).appliesTo (molecule);

            case Xor:

                int trueCnt = 0;
                for (MoleculeRule mr : rules) {
                    if (mr.appliesTo (molecule)) {
                        trueCnt++;
                    }
                }
                return trueCnt % 2 == 1;

        }

        return false;

    }
    public enum Operator {
        And,
        Or,
        Not,
        Xor
    }

}
