<?php

namespace App\Dto\Input;

use ApiPlatform\Metadata\ApiProperty;
use App\Dto\Output\CommandTaskOutput;
use App\Entity\CommandTaskSchedule;
use Symfony\Component\Serializer\Annotation\Groups;

final class CommandTaskScheduleInput
{
    #[Groups(['command-task-schedule:write'])]
    #[ApiProperty(
        description: 'La tarea de comando a programar',
        example: null
    )]
    public ?CommandTaskOutput $commandTask = null;

    #[Groups(['command-task-schedule:write'])]
    #[ApiProperty(
        description: 'El tipo de recurrencia de la programación',
        example: 'daily'
    )]
    public ?string $recurrenceType = null;

    #[Groups(['command-task-schedule:write'])]
    #[ApiProperty(
        description: 'La fecha de ejecución de la tarea',
        example: '2024-01-15T00:00:00+00:00'
    )]
    public ?\DateTimeInterface $executionDate = null;

    #[Groups(['command-task-schedule:write'])]
    #[ApiProperty(
        description: 'La hora de ejecución de la tarea',
        example: '2024-01-15T09:00:00+00:00'
    )]
    public ?\DateTimeInterface $executionTime = null;

    #[Groups(['command-task-schedule:write'])]
    #[ApiProperty(
        description: 'Los detalles de la recurrencia',
        example: ['interval' => 1, 'days' => ['monday', 'wednesday', 'friday']]
    )]
    public ?array $recurrenceDetails = null;

    #[Groups(['command-task-schedule:write'])]
    #[ApiProperty(
        description: 'Si la programación está habilitada',
        example: true
    )]
    public ?bool $enabled = null;

    public function __construct(?CommandTaskSchedule $commandTaskSchedule = null)
    {
        if (!$commandTaskSchedule) {
            return;
        }

        $this->commandTask = new CommandTaskOutput($commandTaskSchedule->getCommandTask());
        $this->recurrenceType = $commandTaskSchedule->getRecurrenceType();
        $this->executionDate = $commandTaskSchedule->getExecutionDate();
        $this->executionTime = $commandTaskSchedule->getExecutionTime();
        $this->recurrenceDetails = $commandTaskSchedule->getRecurrenceDetails();
        $this->enabled = $commandTaskSchedule->isEnabled();
    }

    /**
     * @throws \Exception
     */
    public function createOrUpdateEntity(?CommandTaskSchedule $commandTaskSchedule = null): CommandTaskSchedule
    {
        if (!$commandTaskSchedule) {
            $commandTaskSchedule = new CommandTaskSchedule();
        }

        if ($this->commandTask) {
            $commandTaskSchedule->setCommandTask($this->commandTask->getEntity());
        }
        $commandTaskSchedule->setRecurrenceType($this->recurrenceType);
        $commandTaskSchedule->setExecutionTime($this->executionTime);
        $commandTaskSchedule->setExecutionDate($this->executionDate);
        $commandTaskSchedule->setRecurrenceDetails($this->recurrenceDetails);
        $commandTaskSchedule->setEnabled($this->enabled);

        return $commandTaskSchedule;
    }
}