<?php

namespace App\Dto\Input;

use ApiPlatform\Metadata\ApiProperty;
use App\Dto\Output\RemoteCalendarRuleOutput;
use App\Entity\RemoteCalendar;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;

final class RemoteCalendarInput
{
    #[Groups(['remote-calendar:write'])]
    #[ApiProperty(description: 'The name of the remote calendar', example: "calendar")]
    public ?string $name = null;

    /**
     * @var RemoteCalendarRuleOutput[]
     */
    #[Groups(['remote-calendar:write'])]
    #[ApiProperty(readableLink: false,  writableLink: false)]
    public array $remoteCalendarRules = [];

    public function __construct(?RemoteCalendar $remoteCalendar = null)
    {
        if (!$remoteCalendar) {
            return;
        }

        $this->name = $remoteCalendar->getName();

        if ($remoteCalendar->getRules()) {
            foreach ($remoteCalendar->getRules() as $rule) {
                $this->remoteCalendarRules[] = new RemoteCalendarRuleOutput($rule);
            }
        }
    }

    public function createOrUpdateEntity(?RemoteCalendar $remoteCalendar = null): RemoteCalendar
    {
        if (!$remoteCalendar) {
            $remoteCalendar = new RemoteCalendar();
        }

        $remoteCalendar->setName($this->name);

        foreach ($this->remoteCalendarRules as $rule) {
            $ruleToAdd[] = $rule->getEntity();
        }

        $remoteCalendar->setRules( $ruleToAdd ?? [] );

        return $remoteCalendar;
    }
}