<?php

namespace Comitium5\DesignerBundle\Controller\Widget;

use Comitium5\DesignerBundle\Controller\BaseController;
use Comitium5\DesignerBundle\Entity\Widget;
use Comitium5\DesignerBundle\Entity\WidgetFavorite;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Exception\InvalidParameterException;

/**
 * Class WidgetController
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Controller\Widget
 */
class WidgetController extends BaseController
{
    /**
     * @param Request $request
     * @param Widget $widget
     *
     * @return JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function favoriteAction(Request $request, Widget $widget)
    {
        $favorite = $request->request->get("favorite") === "true" ? true : false;

        $em = $this->get("doctrine.orm.default_entity_manager");
        $repository = $this->get("designer.repository.widget_favorite");
        $user = $this->getUser();

        $widgetFavorite = $repository->findBy(array(
            "widget"  => $widget,
            "user"    => $user->getId(),
        ));

        if ($favorite === true && !$widgetFavorite) {
            $widgetFavorite = new WidgetFavorite($widget, $user->getId());
            $em->persist($widgetFavorite);
        } elseif ($favorite === false && $widgetFavorite instanceof WidgetFavorite) {
            $em->remove($widgetFavorite);
        } else {
            throw new InvalidParameterException();
        }

        $em->flush();

        return new JsonResponse();
    }
}
