<?php

namespace App\Service;

use App\DTO\TaskSchemaRequest;
use App\Entity\Task;
use App\Entity\TaskSchema;
use App\Enum\TaskSchemaStatus;
use Doctrine\ORM\EntityManagerInterface;

class TaskSchemaManager
{
    public function __construct(
        private EntityManagerInterface $em,
        private TaskGenerator $generator,
    ) {
    }

    public function create(TaskSchemaRequest $req): void
    {
        if ($req->repeat === null && $req->date === null) {
            $task = new Task();
            $task->setName($req->name);
            $task->setStatus($req->taskStatus);
            $this->em->persist($task);
            $this->em->flush();

            return;
        }

        $schema = new TaskSchema();
        $schema->setName($req->name);
        $schema->setStatus($req->status);
        $schema->setTaskStatus($req->taskStatus);
        $schema->setDate($req->date);
        $schema->setRepeat($req->repeat);
        $schema->setStart($req->start);
        $schema->setEnd($req->end);
        $this->em->persist($schema);
        $this->em->flush();

        if ($schema->getStatus() === TaskSchemaStatus::Inactive) {
            return;
        }

        $this->generator->generateTasks($schema);
        $this->em->flush();
    }

    public function update(TaskSchema $schema, TaskSchemaRequest $req): void
    {
        $schema->setName($req->name);
        $schema->setStatus($req->status);
        $schema->setTaskStatus($req->taskStatus);
        $schema->setDate($req->date);
        $schema->setRepeat($req->repeat);
        $schema->setStart($req->start);
        $schema->setEnd($req->end);

        if ($schema->getStatus() === TaskSchemaStatus::Inactive) {
            $this->em->flush();

            return;
        }

        $this->generator->removeTasks($schema);
        $this->generator->generateTasks($schema);
        $this->em->flush();
    }

    public function delete(TaskSchema $schema): void
    {
        $this->generator->removeTasks($schema);
        $this->em->remove($schema);
        $this->em->flush();
    }

}
