<?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(array $properties = [])
 */
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);
        $date->setHasDate($beginsAt !== null);
        $date->setBeginsAtSpecificTime($properties['beginsAtSpecificTime'] ?? true);
        $date->setEndsAtSpecificTime($properties['endsAtSpecificTime'] ?? true);

        if (array_key_exists('language', $properties)) {
            $date->setLanguage($properties['language']);
        }
        $date->setEvent($properties['event'] ?? (new EventFactory($this->objectManager))->create());

        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 ];
    }
}
