<?php
namespace App\Controller;

use App\Entity\ActorEntity;
use App\Entity\TaskEntity;
use App\Form\Task\TaskAddForm;
use App\Form\Task\TaskDeleteForm;
use App\Form\Task\TaskEditForm;
use App\Repository\ActorRepository;
use App\Repository\TaskRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGenerator;
use App\Form\Task\TaskFilterForm;

class TaskController extends AbstractExtendedController
{

    /**
     * Page for task list
     *
     * @param Request $request
     * @return Response
     */
    public function tasks(Request $request): Response
    {
        // Get repositories
        $entityManager = $this->getDoctrine()->getManager();
        /** @var ActorRepository $actorRepository */
        $actorRepository = $entityManager->getRepository(ActorEntity::class);
        /** @var TaskRepository $taskRepository */
        $taskRepository = $entityManager->getRepository(TaskEntity::class);

        // Get actors
        $actors = $actorRepository->findAll();

        // Task add form
        /** @var TaskAddForm $taskAddForm */
        $taskAddForm = $this->createNamedCustomForm('taskAdd', TaskAddForm::class, [
            'actors' => $actors,
        ]);
        $taskAddForm->handleRequest($request);
        if ($taskAddForm->isSubmitted() && $taskAddForm->isValid()) {
            $errors = $taskAddForm->validate();
            if (empty($errors)) {
                $task = $taskAddForm->getTask();
                $entityManager->persist($task);
                $entityManager->flush();
                return $this->ajaxFormAnswer([
                    'refresh' => true,
                    'reset' => true,
                ]);
            } else {
                return $this->ajaxFormAnswer([
                    'error' => join('<br/>', $errors),
                    'code' => Response::HTTP_BAD_REQUEST,
                ]);
            }
        }

        // Task delete form
        /** @var TaskDeleteForm $taskDeleteForm */
        $taskDeleteForm = $this->createNamedCustomForm('taskDelete', TaskDeleteForm::class);
        $taskDeleteForm->handleRequest($request);
        if ($taskDeleteForm->isSubmitted() && $taskDeleteForm->isValid()) {
            $errors = $taskDeleteForm->validate();
            if (empty($errors)) {
                $task = $taskDeleteForm->getTask($taskRepository);
                if (!is_null($task)) {
                    $entityManager->remove($task);
                    $entityManager->flush();
                    return $this->ajaxFormAnswer([
                        'refresh' => true,
                    ]);
                }
                return $this->ajaxFormAnswer([
                    'error' => 'Tâche non trouvé',
                    'code' => Response::HTTP_BAD_REQUEST,
                ]);
            } else {
                return $this->ajaxFormAnswer([
                    'error' => join('<br/>', $errors),
                    'code' => Response::HTTP_BAD_REQUEST,
                ]);
            }
        }

        // Filter
        /** @var TaskFilterForm $taskFilterForm */
        $taskFilterForm = $this->createNamedGetCustomForm('taskFilter', TaskFilterForm::class, [
            'actors' => $actors,
        ]);
        $taskFilterForm->handleRequest($request);
        $tasks = $taskFilterForm->getTasks($taskRepository);

        return $this->render('task/tasks.html.twig', [
            'tasks' => $tasks,
            'taskAddForm' => $taskAddForm,
            'taskDeleteForm' => $taskDeleteForm,
            'taskFilterForm' => $taskFilterForm,
        ]);
    }

    /**
     * Page for editing task
     *
     * @param string $id
     * @param Request $request
     * @return Response
     */
    public function task(string $id, Request $request): Response
    {
        // Get repositories
        $entityManager = $this->getDoctrine()->getManager();
        /** @var ActorRepository $actorRepository */
        $actorRepository = $entityManager->getRepository(ActorEntity::class);
        /** @var TaskRepository $taskRepository */
        $taskRepository = $entityManager->getRepository(TaskEntity::class);

        // Get task
        $task = $taskRepository->find($id);

        // Get actors
        $actors = $actorRepository->findAll();

        // Task edit form
        /** @var TaskEditForm $taskEditForm */
        $taskEditForm = $this->createNamedCustomForm('taskEdit', TaskEditForm::class, [
            'actors' => $actors
        ]);
        $taskEditForm->handleRequest($request);
        if ($taskEditForm->isSubmitted() && $taskEditForm->isValid()) {
            $errors = $taskEditForm->validate();
            if (empty($errors)) {
                $taskEditForm->updateTask($task);
                $entityManager->persist($task);
                $entityManager->flush();
                return $this->ajaxFormAnswer([
                    'message' => 'Modification enregistrées',
                    'refresh' => true,
                ]);
            } else {
                return $this->ajaxFormAnswer([
                    'error' => 'Tâche non trouvé',
                    'code' => Response::HTTP_BAD_REQUEST,
                ]);
            }
        }

        // Task delete form
        /** @var TaskDeleteForm $taskDeleteForm */
        $taskDeleteForm = $this->createNamedCustomForm('taskDelete', TaskDeleteForm::class);
        $taskDeleteForm->handleRequest($request);
        if ($taskDeleteForm->isSubmitted() && $taskDeleteForm->isValid()) {
            $errors = $taskDeleteForm->validate();
            if (empty($errors)) {
                $entityManager->remove($task);
                $entityManager->flush();
                if (is_null($task->getActivity())) {
                    return $this->ajaxFormAnswer([
                        'redirect' => $this->generateUrl('task_tasks', [], UrlGenerator::ABSOLUTE_PATH),
                    ]);
                } else {
                    return $this->ajaxFormAnswer([
                        'redirect' => $this->generateUrl('activity_activity', [
                            'id' => $task->getActivity()
                                ->getId()
                        ], UrlGenerator::ABSOLUTE_PATH),
                    ]);
                }
                return $this->ajaxFormAnswer([
                    'error' => 'Tâche non trouvé',
                    'code' => Response::HTTP_BAD_REQUEST,
                ]);
            } else {
                return $this->ajaxFormAnswer([
                    'error' => join('<br/>', $errors),
                    'code' => Response::HTTP_BAD_REQUEST,
                ]);
            }
        }

        // Update fields
        $taskEditForm->updateFields($task);

        return $this->render('task/task.html.twig', [
            'task' => $task,
            'taskEditForm' => $taskEditForm,
            'taskDeleteForm' => $taskDeleteForm,
        ]);
    }
}