<?php declare(strict_types = 1);

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

use DateTimeImmutable;
use idoit\Module\SyneticsFlows\Automation\Trigger\Condition\Condition;
use idoit\Module\SyneticsFlows\Automation\Trigger\Condition\TimeCondition;
use idoit\Module\SyneticsFlows\Automation\Trigger\Condition\TimeConditionRange;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\Invocation;

class TimeConditionMatcher implements ConditionMatcher
{
    /**
     * @param Condition $condition
     * @param Invocation $invocation
     * @return bool
     */
    public function isMatched(Condition $condition, Invocation $invocation): bool
    {
        if (!$condition instanceof TimeCondition) {
            return false;
        }

        $currentDT = new DateTimeImmutable('now');
        $currentTime = $currentDT->format('H:i');
        $currentWeekday = date('w');

        foreach ($condition->getRanges() as $range) {
            if (!$range instanceof TimeConditionRange) {
                continue;
            }

            if ((int)$currentWeekday !== (int)$range->getWeekday()) {
                continue;
            }

            if ($range->getStartTime() <= $range->getEndTime()
                && $range->getStartTime() <= $currentTime
                && $currentTime <= $range->getEndTime()
            ) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param Condition $condition
     * @param Invocation $invocation
     * @return bool
     */
    public function supports(Condition $condition, Invocation $invocation): bool
    {
        return $condition instanceof TimeCondition;
    }
}
