<?php

namespace App\Controller;

use App\Entity\Comment;
use App\Entity\Post;
use App\Form\CommentType;
use App\Form\PostType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\String\Slugger\AsciiSlugger;

class PostController extends AbstractController
{
    /**
     * @Route("/{page}", name="home")
     * @param int $page
     * @return Response
     */
    public function index(int $page = 0): Response
    {
        $repo = $this->getDoctrine()->getRepository(Post::class);
        $pages = (int) round(count($repo->getPublished())/5, 0, PHP_ROUND_HALF_UP);
        if ($page < 0) {
            $page = 0;
        } else if ($page > $pages) {
            $page = $pages;
        }
        return $this->render('home/index.html.twig', [
            'posts' => $repo->getPublished($page*5, 5),
            'pages' => $pages-1,
            'page' => $page
        ]);
    }

    /**
     * @Route("/post/{slug}", name="post")
     * @param Request $request
     * @param string $slug
     * @return Response
     */
    public function post(Request $request, string $slug): Response
    {
        $post = $this->getDoctrine()->getRepository(Post::class)->findOneBy(array('slug' => $slug));
        if (!$post) {
            throw $this->createNotFoundException("Post not found");
        }
        $form = $this->commentFormGenerator($post);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $comment = $form->getData();
            $comment->setCreatedAt(new \DateTime());
            $manager = $this->getDoctrine()->getManager();
            $manager->persist($comment);
            $manager->flush();
            $form = $this->commentFormGenerator($post);
        }
        return $this->render('post/index.html.twig', [
            'post' => $post,
            'form' => $form->createView()
        ]);
    }

    /**
     * @Route("/admin/posts", name="posts")
     */
    public function posts(): Response
    {
        return $this->render('post/posts.html.twig', [
            'posts' => $this->getDoctrine()->getRepository(Post::class)->findBy(array(), array('publishedAt' => 'DESC'))
        ]);
    }

    /**
     * @Route("/admin/posts/add", name="post-add")
     * @param Request $request
     * @return Response
     */
    public function add(Request $request): Response
    {
        $post = new Post();
        $form = $this->createForm(PostType::class, $post);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $post = $form->getData();
            $post->setSlug((new AsciiSlugger())->slug($post->getTitle()));
            $manager = $this->getDoctrine()->getManager();
            $manager->persist($post);
            $manager->flush();
            return $this->redirectToRoute('posts');
        }
        return $this->render('post/posts-form.html.twig', [
            'form' => $form->createView(),
            'title' => 'Add new post'
        ]);
    }

    /**
     * @Route("/admin/posts/edit/{slug}", name="post-edit")
     * @param Request $request
     * @param string $slug
     * @return Response
     */
    public function edit(Request $request, string $slug): Response
    {
        $manager = $this->getDoctrine()->getManager();
        $post = $manager->getRepository(Post::class)->findOneBy(array('slug' => $slug));
        if (!$post) {
            throw $this->createNotFoundException("Post not found");
        }
        $form = $this->createForm(PostType::class, $post);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $post = $form->getData();
            $post->setUpdatedAt(new \DateTime());
            $post->setSlug((new AsciiSlugger())->slug($post->getTitle()));
            $manager->flush();
            return $this->redirectToRoute('posts');
        }
        return $this->render('post/posts-form.html.twig', [
            'form' => $form->createView(),
            'title' => 'Edit '.$post->getTitle()
        ]);
    }

    /**
     * @Route("/admin/posts/remove/{slug}", name="post-remove")
     * @param string $slug
     * @return Response
     */
    public function remove(string $slug): Response
    {
        $manager = $this->getDoctrine()->getManager();
        $post = $manager->getRepository(Post::class)->findOneBy(array('slug' => $slug));
        if (!$post) {
            throw $this->createNotFoundException("Post not found");
        }
        $manager->remove($post);
        $manager->flush();
        return $this->redirectToRoute('posts');
    }

    private function commentFormGenerator(Post $post) : FormInterface
    {
        $comment = new Comment();
        $comment->setPost($post);
        return $this->createForm(CommentType::class, $comment);
    }
}