<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 */

namespace Sso\WebserviceBundle\Services\UserGroup\Search;

use Sso\WebserviceBundle\Entity\Webservice\Type\UserGroup;
use Sso\WebserviceBundle\ErrorHandler\ErrorHandlerInterface;
use Sso\WebserviceBundle\Event\Factory as EventFactory;
use Sso\WebserviceBundle\Event\UserGroupResponseEvent;
use Sso\WebserviceBundle\Exception\InvalidRequestException;
use Sso\WebserviceBundle\Database\Webservice\UserGroup as UserGroupRepository;
use Sso\WebserviceBundle\Services\HandlerInterface;
use Sso\WebserviceBundle\Services\RequestInterface as ServiceRequestInterface;
use Sso\WebserviceBundle\Services\RequestInterface;
use Sso\WebserviceBundle\Services\ResponseBuilderInterface as ServiceResponseBuilderInterface;
use Sso\WebserviceBundle\Services\ResponseBuilderInterface as ServicesResponseBuilderInterface;
use Sso\WebserviceBundle\Services\UserGroup\Search\ResponseData\Factory as ResponseDataFactory;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * Class Handler
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\WebserviceBundle\Services\UserGroup\Search
 */
final class Handler implements HandlerInterface
{
    /**
     * @var RequestParserInterface
     */
    private $requestParser;

    /**
     * @var ResponseBuilderInterface|ServicesResponseBuilderInterface
     */
    private $responseBuilder;

    /**
     * @var ErrorHandlerInterface
     */
    private $errorHandler;

    /**
     * @var UserGroupRepository
     */
    private $repository;

    /**
     * @var ResponseDataFactory
     */
    private $responseDataFactory;

    /**
     * @var EventDispatcherInterface
     */
    private $eventDispatcher;

    /**
     * @var EventFactory
     */
    private $eventFactory;

    /**
     * Handler constructor.
     * @param RequestParserInterface $requestParser
     * @param ServicesResponseBuilderInterface|ResponseBuilderInterface $responseBuilder
     * @param ErrorHandlerInterface $errorHandler
     * @param UserGroupRepository $repository
     * @param ResponseDataFactory $responseDataFactory
     * @param EventDispatcherInterface $eventDispatcher
     * @param EventFactory $eventFactory
     */
    public function __construct(
        RequestParserInterface $requestParser,
        $responseBuilder,
        ErrorHandlerInterface $errorHandler,
        UserGroupRepository $repository,
        ResponseDataFactory $responseDataFactory,
        EventDispatcherInterface $eventDispatcher,
        EventFactory $eventFactory
    ) {
        $this->requestParser = $requestParser;
        $this->responseBuilder = $responseBuilder;
        $this->errorHandler = $errorHandler;
        $this->repository = $repository;
        $this->responseDataFactory = $responseDataFactory;
        $this->eventDispatcher = $eventDispatcher;
        $this->eventFactory = $eventFactory;
    }

    /**
     * @param ServiceRequestInterface $request
     * @return ServiceResponseBuilderInterface
     */
    public function handle(ServiceRequestInterface $request)
    {
        try {
            $requestData = $this->parseRequest($request);
            $userGroupModels = $this->repository->findAll($requestData->getLimit(), $requestData->getOffset());
            $this->buildResponse(
                $userGroupModels,
                $this->repository->countAll(),
                $requestData->getLimit(),
                $requestData->getOffset()
            );
        } catch (InvalidRequestException $exception) {
            if (!$this->errorHandler->hasErrors()) {
                $this->errorHandler->addError(500, 'CriticalError', 'ug400', '', '');
            }
        }

        return $this->responseBuilder;
    }

    /**
     * @param RequestInterface $request
     * @return RequestData\Request
     * @throws InvalidRequestException
     */
    private function parseRequest(RequestInterface $request): RequestData\Request
    {
        $requestData = $this->requestParser->parse($request->getRequestBody());
        if ($this->errorHandler->hasErrors()) {
            throw new InvalidRequestException();
        }
        return $requestData;
    }

    /**
     * @param UserGroup[] $userGroups
     * @param int $count
     * @param int $limit
     * @param int $offset
     */
    private function buildResponse($userGroups, int $count, int $limit, int $offset)
    {
        $responseData = $this->responseDataFactory->response();
        $responseData->setCount($count);
        $responseData->setLimit($limit);
        $responseData->setOffset($offset);

        $responseUserGroupsData = [];
        foreach ($userGroups as $userGroup) {
            $userGroupData = $this->responseDataFactory->userGroup();
            $userGroupData->setId($userGroup->getId());
            $userGroupData->setName($userGroup->getName());
            $userGroupData->setDescription($userGroup->getDescription());
            $userGroupData->setCreatedAt($userGroup->getCreatedAt());
            $userGroupData->setUpdatedAt($userGroup->getUpdatedAt());
            $responseUserGroupsData[] = $userGroupData;
        }

        $event = $this->eventFactory->userGroupResponseEvent($responseUserGroupsData);
        $this->eventDispatcher->dispatch(UserGroupResponseEvent::RESPONSE_EVENT, $event);
        $responseData->setUserGroups($event->getUserGroupData());

        $this->responseBuilder->setResponse($responseData);
    }
}
