<?php

namespace App\Controller;

use App\Entity\Category;
use App\Form\CategoryType;
use App\Service\CategoryService;
use App\Service\DataGrid\DataGrid;
use App\Service\DataGrid\DataGridFilterQuery;
use App\Service\DataGrid\DataGridHeader;
use App\Service\DataGrid\DataGridNavigation;
use App\Service\DataGrid\DataGridSort;
use Doctrine\ORM\EntityNotFoundException;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\View\View;
use Limenius\Liform\Liform;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class CategoryController extends FOSRestController
{
    private $categoryService;

    public function __construct(CategoryService $categoryService)
    {
        $this->categoryService = $categoryService;
    }

    /**
     * Retrieves a collection of Category resource.
     *
     * @Rest\Get("/category/grid")
     * @Rest\View(serializerGroups={"grid"})
     *
     * @param Request $request
     *
     * @return View
     */
    public function getGridCategory(Request $request): View
    {
        $dataGrid = new DataGrid();

        $dataGrid
            ->setName('category')
            ->addHeader(new DataGridHeader(['label' => 'Name', 'id' => 'title', 'isSortable' => true]));

        $dataGrid->setNavigation(new DataGridNavigation(['page' => $request->get('page'), 'rpp' => $request->get('rpp')]));

        $dataGrid->addSorter(new DataGridSort(['sort' => $request->get('sort'), 'order' => $request->get('order')]));

        $dataGrid->addFilter(new DataGridFilterQuery($request->get('q')));

        $dataGrid->setData($this->categoryService->getCategoriesByGrid($dataGrid))
            ->setTotal($this->categoryService->countCategoriesByGrid($dataGrid));

        // In case our GET was a success we need to return a 200 HTTP OK response with the collection of article object
        return View::create($dataGrid, Response::HTTP_OK);
    }

    /**
     * Retrieves a collection of Category resource.
     *
     * @Rest\Get("/category")
     *
     * @return View
     */
    public function getAllCategories(): View
    {
        $categorys = $this->categoryService->getAllCategories();

        // In case our GET was a success we need to return a 200 HTTP OK response with the collection of article object
        return View::create($categorys, Response::HTTP_OK);
    }

    /**
     * Retrieves an category resource.
     *
     * @Rest\Get("/category/{categoryId}", requirements={"categoryId"="\d+"}))
     *
     * @param int $categoryId
     *
     * @return View
     */
    public function getCategory(int $categoryId): View
    {
        try {
            $category = $this->categoryService->getCategory($categoryId);

            return View::create($category, Response::HTTP_OK);
        } catch (EntityNotFoundException $e) {
            return View::create(['code' => Response::HTTP_NOT_FOUND, 'message' => $e->getMessage()], Response::HTTP_NOT_FOUND);
        }
    }

    /**
     * Creates an category resource.
     *
     * @Rest\Post("/category")
     *
     * @param Request $request
     *
     * @return View
     */
    public function postCategory(Request $request): View
    {
        $form = $this->createForm(CategoryType::class, null, ['csrf_protection' => false]);

        $form->submit($request->request->all());

        if ($form->isSubmitted() && $form->isValid()) {
            $category = $this->categoryService->saveCategory($form->getData());
            // In case our POST was a success we need to return a 201 HTTP CREATED response
            return View::create($category, Response::HTTP_CREATED);
        }

        return View::create($form, Response::HTTP_BAD_REQUEST);
    }

    /**
     * Replaces Category resource.
     *
     * @Rest\Put("/category/{categoryId}")
     *
     * @param Request $request
     * @param int     $categoryId
     *
     * @return View
     */
    public function putCategory(Request $request, int $categoryId): View
    {
        try {
            $category = $this->categoryService->getCategory($categoryId);
        } catch (EntityNotFoundException $e) {
            return View::create(['code' => Response::HTTP_NOT_FOUND, 'message' => $e->getMessage()], Response::HTTP_NOT_FOUND);
        }

        $form = $this->createForm(CategoryType::class, $category, ['csrf_protection' => false]);
        $form->submit($request->request->all());

        if ($form->isSubmitted() && $form->isValid()) {
            $category = $this->categoryService->saveCategory($category);

            // In case our POST was a success we need to return a 201 HTTP CREATED response
            return View::create($category, Response::HTTP_OK);
        }

        // In case our PUT was a success we need to return a 200 HTTP OK response with the object as a result of PUT
        return View::create($form, Response::HTTP_BAD_REQUEST);
    }

    /**
     * Updates Category resource.
     *
     * @Rest\Patch("/category/{categoryId}")
     *
     * @param Request $request
     * @param int     $categoryId
     *
     * @return View
     */
    public function patchCategoryAction(Request $request, int $categoryId): View
    {
        try {
            $category = $this->categoryService->getCategory($categoryId);
        } catch (EntityNotFoundException $e) {
            return View::create(['code' => Response::HTTP_NOT_FOUND, 'message' => $e->getMessage()], Response::HTTP_NOT_FOUND);
        }

        $form = $this->createForm(CategoryType::class, $category, ['csrf_protection' => false]);
        $form->submit($request->request->all(), false);

        if ($form->isSubmitted() && $form->isValid()) {
            $category = $this->categoryService->saveCategory($form->getData());

            // In case our PUT was a success we need to return a 200 HTTP OK response with the object as a result of PATCH
            return View::create($category, Response::HTTP_OK);
        }

        // In case our PATCH wasn't a success we need to return a 400 HTTP BAD REQUEST response with the form object as a result
        return View::create($form, Response::HTTP_BAD_REQUEST);
    }

    /**
     * Removes the Category resource.
     *
     * @Rest\Delete("/category/{categoryId}")
     *
     * @param int $categoryId
     *
     * @return View
     */
    public function deleteCategory(int $categoryId): View
    {
        try {
            $category = $this->categoryService->getCategory($categoryId);
        } catch (EntityNotFoundException $e) {
            return View::create(['code' => Response::HTTP_BAD_REQUEST, 'message' => $e->getMessage()], Response::HTTP_BAD_REQUEST);
        }

        $this->categoryService->deleteCategory($category);
        // In case our DELETE was a success we need to return a 204 HTTP NO CONTENT response. The object is deleted.
        return View::create([], Response::HTTP_NO_CONTENT);
    }

    /**
     * Return serialized form to create resource.
     *
     * @Rest\Get("/category/schema")
     *
     * @param Liform $liform
     *
     * @return View
     */
    public function getSchema(Liform $liform): View
    {
        $category = new Category();

        $form = $this->createForm(CategoryType::class, $category, ['csrf_protection' => false]);

        $form = $liform->transform($form);

        return View::create($form, Response::HTTP_OK);
    }
}
