<?php

namespace AppBundle\Controller\Api;

use AppBundle\Entity\Ad;
use AppBundle\Representation\Ads;
use AppBundle\Representation\SingleAd;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Post;
use FOS\RestBundle\Controller\Annotations\View;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Request\ParamFetcherInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use JMS\Serializer\SerializationContext;
use Symfony\Component\HttpFoundation\JsonResponse;

class AdController extends FOSRestController
{
    /**
     * @Rest\Get(path="/api/ads/{id}", name="api_ad_show", requirements={"id"="\d+"})
     * @Rest\View
     *
     */
    public function showAction(Ad $ad)
    {
        // return $ad;
        //return new SingleAd($ad);

        $data = $this->get('jms_serializer')->serialize($ad, 'json', SerializationContext::create()->setGroups(array('ad_detail')));
        return new JsonResponse($data, 200, [], true);
    }

    /**
     * @Rest\Get("/api/ads", name="api_ad_list")
     * 
     * @Rest\QueryParam(
     *     name="keyword",
     *     requirements="\w+",
     *     nullable=true,
     *     description="The keyword to search for."
     * )
     * @Rest\QueryParam(
     *     name="order",
     *     requirements="asc|desc",
     *     default="asc",
     *     description="Sort order (asc or desc)"
     * )
     * @Rest\QueryParam(
     *     name="limit",
     *     nullable=true,
     *     requirements="\d+",
     *     default="15",
     *     description="Max number of ads per page."
     * )
     * @Rest\QueryParam(
     *     name="offset",
     *     nullable=true,
     *     requirements="\d+",
     *     default="1",
     *     description="The pagination offset"
     * )
     * @Rest\QueryParam(
     *     name="isPromoted",
     *     requirements="\d+",
     *     nullable=true,
     *     description="Ads are satisfied (pourvues) or not "
     * )   
     * 
     * @Rest\QueryParam(
     *     name="isEmphasis",
     *     requirements="\d+",
     *     nullable=true,
     *     description="Ads are promoted -mise en avant"
     * )
     * 
     * @Rest\QueryParam(
     *     name="status",
     *     requirements="\w+",
     *     nullable=true,
     *     description="Ads filtered by status (PUBLISHED, DISABLE, DRAFT, CLOSED, DECLINED)"
     * )
     *
     * @Rest\View(statusCode=200, serializerGroups={"ad_list"})
     */
    public function listAction(ParamFetcherInterface $paramFetcher)
    {
        $pager = $this->getDoctrine()->getRepository('AppBundle:Ad')->search(
            $paramFetcher->get('keyword'),
            $paramFetcher->get('order'),
            $paramFetcher->get('limit'),
            $paramFetcher->get('offset'),
            $paramFetcher->get('status'),
            $paramFetcher->get('isPromoted'),
            $paramFetcher->get('isEmphasis')
        );

        return new Ads($pager);
    }

    /**
     * @Rest\Post("/api/ads", name="api_ad_create")
     * @Rest\View(StatusCode = 201)
     * @ParamConverter("ad", converter="fos_rest.request_body")
     */
    public function createAction(Ad $ad)
    {
        $em = $this->getDoctrine()->getManager();
        $em->persist($ad);
        $em->flush();
        return $this->view(
            new SingleAd($ad),
            Response::HTTP_CREATED,
            ['Location' => $this->generateUrl('api_ad_show', ['id' => $ad->getId(), UrlGeneratorInterface::ABSOLUTE_URL])]
        );
    }

    /**
     * @Rest\Get("/api/adAjaxRecStat/{id}", name="adAjaxRecStat")
     * @Rest\View(statusCode=200)
     */
    public function adAjaxRecStatAction(Ad $ad)
    {
        $history = $this->get('edeclic.history.record');
        if ($this->getUser()) {
            $idUser = $this->getUser()->getId();
            $history->recordIt($idUser, "r", get_class($ad), $ad->getId(), serialize($ad));
        } else {
            $history->recordIt("Anonymous", "r", get_class($ad), $ad->getId(), serialize($ad));
        }

        return new JsonResponse(array('code' => "ok"));
    }
}
