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

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 DbManager;
use Sso\WebserviceBundle\Entity\Webservice\Type\User as ModelUser;
use Sso\WebserviceBundle\Services\UserApplication\Delete\RequestData\User as RequestDataUser;

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

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

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

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

    /**
     * @param ServiceRequestInterface $request
     * @return ServiceResponseBuilderInterface
     */
    public function handle(ServiceRequestInterface $request)
    {

        $requestModel = $this->factory->request()->requestParser()->parse($request->getRequestBody());

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

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

        //ok next step set the responseData
        $force = $requestModel->getApplicationType()->isForce();
        $appToDelete = $requestModel->getApplicationType()->getName();

        //first check if the user has this application
        $userHasApplication = false;
        foreach ($userModel->getUserApplications() as $userApplication) {
            if ($userApplication->getName() === $appToDelete) {
                $userHasApplication = true;
                $userApplicationDelete = $userApplication;
            }
        }

        if (!$userHasApplication) {
            $this->errorHandler->addError(404, 'UserApplicationNotFound', 'uad2018', '', '');
            return $responseBuilder;
        }

        //now delete application
        if ($force) {
            //delete roles and attributes first
            $this->database->userApplication()->removeApplicationForce($userApplicationDelete);
        } else {

            if (!$this->database->userApplication()->removeUserApplication($userApplicationDelete)) {
                //we have to referesh the entity before

                foreach ($userApplicationDelete->errors()->getErrors() as $error) {
                    $this->errorHandler->addError(400, 'UserApplicationNotFound', 'uad2018',
                        $error->longMessage ? $error->longMessage : $error->shortMessage, '');
                }

                return $responseBuilder;
            }
        }

        $responseData = $this->factory->responseData()->response()->setStatus(200)->setMessage('UserApplication Deleted');

        $responseBuilder->setResponse($responseData);

        return $responseBuilder;
    }

    /**
     * @param RequestDataUser $requestModel
     * @return ModelUser|null
     */
    private function getUserModel(RequestDataUser $requestModel)
    {
        if ($identifier = $requestModel->getIdentifier()) {
            return $this->database->user()->getUserByIdentifier($identifier);
        }
        if ($guid = $requestModel->getGuid()) {
            return $this->database->user()->getUserByGuid($guid);
        }
        if ($username = $requestModel->getUsername()) {
            return $this->database->user()->getUserByUsername($username);
        }
        if ($email = $requestModel->getEmail()) {
            return $this->database->user()->getUserByEmail($email);
        }
        return null;
    }
}
