<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Automation\Trigger\ConditionMatcher;

use idoit\Module\SyneticsFlows\Automation\Trigger\Condition\Condition;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\Invocation;

class ArrayConditionMatcher implements ConditionMatcher
{
    private array $conditionMatchers = [];

    /**
     * @param ConditionMatcher $matcher
     *
     * @return void
     */
    public function add(ConditionMatcher $matcher): void
    {
        $this->conditionMatchers[] = $matcher;
    }

    /**
     * @param Condition $condition
     * @param Invocation $invocation
     *
     * @return bool
     */
    public function isMatched(Condition $condition, Invocation $invocation): bool
    {
        foreach ($this->conditionMatchers as $matcher) {
            if (!$matcher instanceof ConditionMatcher || !$matcher->supports($condition, $invocation)) {
                continue;
            }

            return $matcher->isMatched($condition, $invocation);
        }

        return true;
    }

    /**
     * @param Condition $condition
     * @param Invocation $invocation
     *
     * @return bool
     */
    public function supports(Condition $condition, Invocation $invocation): bool
    {
        /** @var ConditionMatcher $matcher */
        foreach ($this->conditionMatchers as $matcher) {
            if ($matcher->supports($condition, $invocation)) {
                return true;
            }
        }

        return false;
    }
}
