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

namespace Sso\WebserviceBundle\Services\PasswordPolicy\Show;

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\Webservice\Manager as DataBaseWebservice;
use Sso\WebserviceBundle\Entity\Webservice\Type\User as ModelUser;
use Sso\WebserviceBundle\Entity\Webservice\Type\PasswordPolicy as ModelPasswordPolicy;
use Sso\WebserviceBundle\Services\PasswordPolicy\Show\RequestData\PasswordPolicy as RequestDataPasswordPolicy;

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

    /**
     * @var DataBaseWebservice
     */
    private $database;

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

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

    /**
     * @param ServiceRequestInterface $request
     * @return ServiceResponseBuilderInterface
     * @throws \Exception
     */
    public function handle(ServiceRequestInterface $request)
    {
        $requestModel = $this->factory->request()->requestParser()->parse($request->getRequestBody());

        $responseBuilder = $this->factory->response()->responseBuilder();
        if ($this->errorHandler->hasErrors()) {
            return $responseBuilder;
        }

        if (null !== $requestModel->getIdentifier()) {
            $userModel = $this->getUserModel($requestModel);
            if (null === $userModel) {
                $this->errorHandler->addError(404, 'UserNotFound', 'pp0001', '', '');
                return $responseBuilder;
            }

            $passwordPolicyModel = $this->database->user()->getUsersPasswordPolicy($userModel);

            if (null === $passwordPolicyModel) {
                $responseData = $this->factory->responseData()->passwordPolicy()->setFromUserModel($userModel);
            } else {
                $responseData = $this->factory->responseData()->passwordPolicy()->setBoth(
                    $userModel,
                    $passwordPolicyModel
                );
            }

        } else {
            //only check for policy and map
            $passwordPolicyModel = $this->getPasswordPolicyModel($requestModel);
            if (null === $passwordPolicyModel) {
                $this->errorHandler->addError(404, 'PasswordPolicyNotFound', 'pp0002', '', '');
                return $responseBuilder;
            }
            $responseData = $this->factory->responseData()->passwordPolicy()->setFromPasswordPolicyModel($passwordPolicyModel);
        }

        $responseBuilder->setResponse($responseData);

        return $responseBuilder;
    }

    /**
     * @param RequestDataPasswordPolicy $requestModel
     * @return ModelUser|null
     * @throws \Exception
     */
    private function getUserModel(RequestDataPasswordPolicy $requestModel)
    {
        if ($identifier = $requestModel->getIdentifier()) {
            return $this->database->user()->getUserByIdentifier($identifier);
        }
        return null;
    }

    /**
     * @param RequestDataPasswordPolicy $requestModel
     * @return ModelPasswordPolicy|null
     * @throws \Exception
     */
    private function getPasswordPolicyModel(RequestDataPasswordPolicy $requestModel)
    {
        if ($policyId = $requestModel->getPolicyId()) {
            return $this->database->passwordPolicy()->getOne($policyId);
        }
        return null;
    }
}
