<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Automation\Trigger\TriggerType\Repetition;

use DateInterval;
use DateTimeImmutable;
use Exception;
use idoit\Module\SyneticsFlows\Validation\Required;

class WeekRepetition extends Repetition
{
    /**
     * @param int $period
     * @param int[] $weekDays
     */
    public function __construct(
        int $period,
        #[Required]
        protected array $weekDays = [],
    )
    {
        parent::__construct($period);
    }

    /**
     * @return int[]
     */
    public function getWeekDays(): array
    {
        return $this->weekDays;
    }

    /**
     * @param DateTimeImmutable $start
     * @param DateTimeImmutable $offset
     *
     * @return int
     *
     * @throws Exception
     */
    protected function getIterationNumber(DateTimeImmutable $start, DateTimeImmutable $offset): int
    {
        $offsetInSeconds = max(0, $offset->getTimestamp() - $start->getTimestamp());
        $period = $this->period * 7 * 24 * 60 * 60;
        return (int)floor($offsetInSeconds / $period);
    }

    /**
     * @param DateTimeImmutable $start
     * @param int $iteration
     *
     * @return DateTimeImmutable[]
     *
     * @throws Exception
     */
    protected function getNextIterationDates(DateTimeImmutable $start, int $iteration): array
    {
        $targetWeek = $start->add(new DateInterval('P' . ($iteration * $this->period) . 'W'));
        $result = [];
        for ($i = 0; $i < 7; ++$i) {
            $date = $targetWeek->add(new DateInterval('P' . $i . 'D'));
            $weekday = (int)$date->format('w');
            if (in_array($weekday, $this->weekDays, true)) {
                $result[] = $date;
            }
        }

        return $result;
    }
}
