<?php

namespace Bundle\MainBundle\Controller;

use Bundle\CommonBundle\Entity\MainSettings\MainSettingsRepository;
use Bundle\CommonBundle\Entity\UsersBadges\UsersBadgesRepository;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Bundle\CommonBundle\Controller\BaseController;
use Bundle\CommonBundle\Response\JsonResponse;

/**
 * Badge\Badge controller.
 *
 * @Route("/badge")
 */
class BadgeController extends BaseController
{
    /**
     * @Route("/list", name="badge_list");
     * @Template("MainBundle:Awards:badgeListPopup.html.twig")
     */
    public function listAction(Request $request)
    {
        $badges = $this->getRepository('badge')->findAll();

        return array(
            'badgeList' => $badges
        );
    }

    /**
     * Отправить бейджи
     * @Route("/send", name="badges_send")
     * @Method("POST")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function sendAction(Request $request)
    {
        $badgeId = (int)$request->get('badge');
        // Id пользователя, с чьей страницы был отправлен бейдж
        $userId = (int)$request->get('userId');
        $view = array();

        $receivers = $request->get('receivers', null);
        if (is_array($receivers)) {
            $receivers = array_values(array_unique($receivers));
        } else {
            return $this->generateError('badge.receivers');
        }
        
        if (!$badgeId) {
            return $this->generateError('badge.notFound');
        }

        try {

            /** @var UsersBadgesRepository $usersBadgesRepository */
            $usersBadgesRepository = $this->getRepository('usersbadges');

            if (!$usersBadgesRepository->checkReceivers($receivers)) {
                return $this->generateError('badge.receivers');
            }

            if (!$badge = $this->getRepository('badge')->find($badgeId)) {
                return $this->generateError('badge.notFound');
            }

            $canSend = $usersBadgesRepository->canSendCount($this->getUser());
            /** @var MainSettingsRepository $mainSettingsRepository */
            $mainSettingsRepository = $this->getRepository('mainSettings');
            if ($canSend < 1 || count($receivers) > $canSend) {
                return $this->generateError('badge.sendLimitExceeded', null, 'homepage', null, array('%NUM%' => $mainSettingsRepository->getSendBadgesPerDay()));
            }

            $this->getRepository('usersbadges')->sendBadgeTo($badge, $receivers, $request->get('comment'));

            if ($userId && $userId != $this->getUser()->getId()) {
                /** @var User $user */
                if (!$user = $this->getRepository('user')->find($userId)) {
                    return $this->generateError('user.notFound');
                }
                $view['.user-badge-rating'] = $this->renderView('MainBundle:Awards:userBadges.html.twig', array(
                    'userRating' => $this->getRepository('badge')->getUserRating($user)
                ));
            }

            $view['.top-badge-rating'] = $this->renderView('MainBundle:Awards:topBadgeRating.html.twig', array(
                'badgeRating' => $this->getRepository('badge')->getRating()
            ));
            $view['.js-main-wall'] = $this->forward('MainBundle:Wall:index')->getContent();

        } catch (\Exception $ex) {
	        $this->container->get('my_logger')->log($ex, $this->getUser());

	        return $this->generateError('repository.save', $ex);
        }

        $response = new JsonResponse();
        $response->setJsonContent(
            array(
                'view' => $view
            )
        );

        return $response;
    }

    /**
     * Finds and displays a UsersBadges\UsersBadges entity.
     *
     * Route("/my_badges", name="my_badges_list")
     * @Method("GET")
     * @Template()
     */
    public function showAction()
    {
        $badges = $this->getRepository('usersbadges')->getBadgesForUser($this->getUser()->getId());

        return array(
            'badges' => $badges
        );
    }
}
