<?php

namespace RTMCustomMails\Rest\Model;


use DateTimeInterface;
use Symfony\Component\Serializer\Annotation\Context;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;

class ScheduledEmail
{

    protected int $id; // the action ID

    protected string $emailId; // the email ID

    protected string $status;

    protected array $parameters;

    #[Context(normalizationContext: [DateTimeNormalizer::FORMAT_KEY => DateTimeInterface::ATOM])]
    protected DateTimeInterface $time;

    protected function __construct()
    {
    }

    /**
     * @return int
     */
    public function getId(): int
    {
        return $this->id;
    }

    /**
     * @param int $id
     * @return ScheduledEmail
     */
    public function setId(int $id): ScheduledEmail
    {
        $this->id = $id;
        return $this;
    }

    /**
     * @return string
     */
    public function getEmailId(): string
    {
        return $this->emailId;
    }

    /**
     * @param string $id
     * @return ScheduledEmail
     */
    public function setEmailId(string $id): ScheduledEmail
    {
        $this->emailId = $id;
        return $this;
    }

    /**
     * @return string
     */
    public function getStatus(): string
    {
        return $this->status;
    }

    /**
     * @param string $status
     * @return ScheduledEmail
     */
    public function setStatus(string $status): ScheduledEmail
    {
        $this->status = $status;
        return $this;
    }

    /**
     * @return array
     */
    public function getParameters(): array
    {
        return $this->parameters;
    }

    /**
     * @param array $parameters
     * @return ScheduledEmail
     */
    public function setParameters(array $parameters): ScheduledEmail
    {
        $this->parameters = $parameters;
        return $this;
    }

    /**
     * @return DateTimeInterface
     */
    public function getTime(): DateTimeInterface
    {
        return $this->time;
    }

    /**
     * @param DateTimeInterface $time
     * @return ScheduledEmail
     */
    public function setTime(DateTimeInterface $time): ScheduledEmail
    {
        $this->time = $time;
        return $this;
    }

    public static function fromAsAction(int $id, string $status, \ActionScheduler_Action $action)
    {
        $scheduledEmail = new ScheduledEmail();
        $args = $action->get_args();

        // schedule dates are stored as ActionScheduler_DateTime objects, which are not normalizable
        // by the DateTimeNormalizer????
        $time = $action->get_schedule()->next()->getTimestamp();
        $time = new \DateTime('@' . $time);

        $scheduledEmail
            ->setId($id)
            ->setEmailId($args['email_id'])
            ->setTime($time)
            ->setParameters($args['args'])
            ->setStatus($status);
        return $scheduledEmail;
    }

}