<?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  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\WebserviceBundle\Services\UserSearch\FindByApplicationRole;

use Sso\WebserviceBundle\ErrorHandler\ErrorHandlerInterface;
use Sso\WebserviceBundle\Services\HandlerInterface;
use Sso\WebserviceBundle\Services\RequestInterface as ServiceRequestInterface;
use Sso\WebserviceBundle\Services\ResponseBuilderInterface as ServiceResponseBuilderInterface;
use Sso\WebserviceBundle\Database\Manager as DatabaseManager;
use Sso\WebserviceBundle\Entity\Webservice\Type\User as ModelUser;
use Sso\WebserviceBundle\Services\UserSearch\FindByApplicationRole\RequestData\UserSearch as RequestDataUser;


/**
 * Class Handler
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package Sso\WebserviceBundle\Services\User\ShowDetails
 */
final class Handler implements HandlerInterface
{
    /**
     * @var Factory
     */
    private $factory;

    /**
     * @var DatabaseManager
     */
    private $dbM;

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

    /**
     * Handler constructor.
     * @param Factory $factory
     * @param DatabaseManager $database
     * @param ErrorHandlerInterface $errorHandler
     */
    public function __construct(Factory $factory, DatabaseManager $database, ErrorHandlerInterface $errorHandler)
    {
        $this->factory = $factory;
        $this->dbM = $database;
        $this->errorHandler = $errorHandler;
    }

    /**
     * @param ServiceRequestInterface $request
     * @return ServiceResponseBuilderInterface
     */
    public function handle(ServiceRequestInterface $request)
    {
        //get request DTO
        $requestDTO = $this->factory->request()->requestParser()->parse($request->getRequestBody());

        //set response builder in case of invalid request
        $responseBuilder = $this->factory->response()->responseBuilder();
        if ($this->errorHandler->hasErrors()) {
            return $responseBuilder;
        }

        //check if application exists
        if (!($applicationModel = $this->dbM->webservice()->application()->getApplicationByName($requestDTO->getApplicationName()))) {
            $this->errorHandler->addError(400, 'usfbr2', 'usfbr2001', 'Invalid Application', 'The Application '.$requestDTO->getApplicationName().' does not exist!');
            return $responseBuilder;
        }

        //check read on application
        if(!in_array($requestDTO->getApplicationName(), $this->factory->apiM()->userRolesApplicationRead())){
            $this->errorHandler->addError(400, 'XXX', 'app', 'ApplicationAccessDenied', 'You are not allowed to read this Application '.$requestDTO->getApplicationName().'!');
        }

        // check if role exists for application
        $roles = $applicationModel->getRoles();
        $applicationRole = null;
        foreach( $roles as $role ) {
            if( $role->getName() == $requestDTO->getRoleName() ) {
                $applicationRole = $role;
                break;
            }
        }

        if ( null === $applicationRole ) {
            $this->errorHandler->addError(400, 'usfbr2', 'usfbr2002', 'Invalid Application Role', 'The Application '.$requestDTO->getApplicationName().' does not have a role ' . $requestDTO->getRoleName() . '');
            return $responseBuilder;
        }

        // get user models with given application attribute value
        $usersArray = $this->dbM->webservice()->user()->getGuidNameEmailByApplicationRole( $applicationRole, $requestDTO->getModifiedAfter(), $requestDTO->isRoleActive(), $requestDTO->isApplicationActive());

        //fill DTO response
        $responseData = $this->factory->responseData()->userData()->setFromUsers($usersArray);

        $responseBuilder->setResponse($responseData);

        return $responseBuilder;
    }
}
