<?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\Delete;

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\Delete\ResponseData\Factory as ResponseDataFactory;
use Sso\WebserviceBundle\Services\UserGroup\Delete\RequestData\UserGroup as RequestDataUserGroup;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * Class Handler
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\WebserviceBundle\Services\UserGroup\Delete
 */
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);
            $userGroupModel = $this->getUserGroup($requestData);
            $responseData = $this->buildResponse($userGroupModel);
            $this->deleteUserGroup($userGroupModel, $requestData);
            $this->responseBuilder->setResponse($responseData);
        } catch (InvalidRequestException $exception) {
            if (!$this->errorHandler->hasErrors()) {
                $this->errorHandler->addError(500, 'CriticalError', 'ug100', '', '');
            }
        }

        return $this->responseBuilder;
    }

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

    /**
     * @param RequestData\UserGroup $userGroupType
     * @return UserGroup
     * @throws InvalidRequestException
     */
    private function getUserGroup(RequestData\UserGroup $userGroupType): UserGroup
    {
        $userGroup = $this->repository->findByUserGroupName($userGroupType->getName());
        if (!$userGroup instanceof UserGroup) {
            $this->errorHandler->addError(404, 'UserGroupNotFound', 'ug021', '', '');
            throw new InvalidRequestException();
        }
        return $userGroup;
    }

    /**
     * @param UserGroup $userGroup
     * @param RequestDataUserGroup $requestData
     * @return void
     * @throws InvalidRequestException
     */
    private function deleteUserGroup(UserGroup $userGroup, RequestDataUserGroup $requestData): void
    {
        $userGroup->setName($requestData->getName());
        if (!$this->repository->deleteUserGroup($userGroup)) {
            throw new InvalidRequestException();
        }
    }

    /**
     * @param UserGroup $userGroup
     * @return ResponseData\UserGroup
     */
    private function buildResponse(UserGroup $userGroup): ResponseData\UserGroup
    {
        $responseData = $this->responseDataFactory->userGroup();
        $responseData->setId($userGroup->getId());
        $responseData->setName($userGroup->getName());
        $responseData->setCreatedAt($userGroup->getCreatedAt());
        $responseData->setUpdatedAt($userGroup->getUpdatedAt());
        $responseData->setDeletedAt(new \DateTime());

        $event = $this->eventFactory->userGroupResponseEvent([$responseData]);
        $this->eventDispatcher->dispatch(UserGroupResponseEvent::RESPONSE_EVENT, $event);
        $userGroupsData = $event->getUserGroupData();

        return reset($userGroupsData);
    }
}
