<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Tests\Factory;

use Newland\Toubiz\Sync\Neos\Domain\Model\EventDate;

/**
 * Class EventDateFactory
 *
 * @package Newland\Toubiz\Sync\Neos\Tests\Factory
 * @method EventDate create()
 */
class EventDateFactory extends AbstractFactory
{

    public function make(array $properties = [])
    {
        $date = new EventDate();

        $date->setOriginalId($properties['originalId'] ?? $this->faker->uuid);
        $date->setNote($properties['note'] ?? $this->faker->text);

        [ $beginsAt, $endsAt ] = $this->getBeginAndEndDates($properties);
        $date->setBeginsAt($beginsAt);
        $date->setEndsAt($endsAt);

        if (array_key_exists('language', $properties)) {
            $date->setLanguage($properties['language']);
        }
        if (array_key_exists('event', $properties)) {
            $date->setEvent($properties['event']);
        }
        if (array_key_exists('detailUri', $properties)) {
            $date->setDetailUri($properties['detailUri']);
        }

        return $date;
    }

    /** @return \DateTime[] */
    private function getBeginAndEndDates(array $properties): array
    {
        $beginsAt = $properties['beginsAt'] ?? $this->faker->dateTime();
        $beginsAt = \is_string($beginsAt) ? new \DateTime($beginsAt) : $beginsAt;
        $endsAt = $properties['endsAt'] ?? null;
        $endsAt = \is_string($endsAt) ? new \DateTime($endsAt) : $endsAt;

        if ($endsAt === null) {
            $interval = new \DateInterval('P' . random_int(60, 600). 'M');
            $endsAt = (clone $beginsAt)->add($interval);
        }

        return [ $beginsAt, $endsAt ];
    }
}
