<?php

/**
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected 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\User\ChangePassword\Request\Version3;

use JMS\Serializer\SerializerInterface;
use Sso\WebserviceBundle\ErrorHandler\ErrorHandlerInterface;
use Sso\WebserviceBundle\Services\User\ChangePassword\RequestParserInterface;
use Sso\WebserviceBundle\Services\User\ChangePassword\RequestData\Factory as RequestDataFactory;
use InvalidArgumentException;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Sso\WebserviceBundle\Api\Mapper\Index as AutoMapper;

/**
 * Class RequestParser
 * @package Sso\WebserviceBundle\Services\User\ChangePassword\Request\Version3
 */
class RequestParser implements RequestParserInterface
{
    /**
     * @var SerializerInterface
     */
    private $serializer;

    /**
     * @var RequestDataFactory
     */
    private $factory;

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

    /**
     * @var ValidatorInterface
     */
    private $validator;

    /**
     * @var AutoMapper
     */
    private $autoMapper;

    /**
     * RequestParser constructor.
     * @param SerializerInterface $serializer
     * @param RequestDataFactory $factory
     * @param ErrorHandlerInterface $errorHandler
     * @param ValidatorInterface $validator
     */
    public function __construct(SerializerInterface $serializer, RequestDataFactory $factory, ErrorHandlerInterface $errorHandler, ValidatorInterface $validator, AutoMapper $autoMapper)
    {
        $this->serializer = $serializer;
        $this->factory = $factory;
        $this->errorHandler = $errorHandler;
        $this->validator = $validator;
        $this->autoMapper = $autoMapper;
    }

    /**
     * @param string $content
     * @return \Sso\WebserviceBundle\Services\User\ChangePassword\RequestData\User
     */
    public function parse($content)
    {
        /** @var Request $request */
        $request = $this->serializer->deserialize($content, Request::class, 'xml');

        $user = $this->factory->user();
        if (!$this->validate($request)) {
            return $user;
        }

        $user->setPasswordData($this->getPaswordDTO($request));

        $userType = $request->getUser()->getChangePassword()->getKey()->getKeyUserType();

        if ($identifier = $userType->getIdentifier()) {
            $user->setIdentifier($identifier);
            $request->getUser()->getChangePassword()->getValue()->getPasswordType()->setIdentifier($identifier);

            return $user;
        }
        if ($username = $userType->getUsername()) {
            $user->setUsername($username);
            $request->getUser()->getChangePassword()->getValue()->getPasswordType()->setIdentifier($username);

            return $user;
        }
        if ($guid = $userType->getGuid()) {
            $user->setGuid($guid);
            $request->getUser()->getChangePassword()->getValue()->getPasswordType()->setIdentifier($guid);

            return $user;
        }
        if ($email = $userType->getEmail()) {
            $user->setEmail($email);
            $request->getUser()->getChangePassword()->getValue()->getPasswordType()->setIdentifier($email);

            return $user;
        }

        $this->errorHandler->addError(400, 'uu2', 'uu001', 'Wrong user data', 'No valid identifier found');

        return $user;
    }

    /**
     * @param Request $request
     * @return bool
     */
    private function validate(Request $request)
    {
        $validationErrors = $this->validator->validate($request);
        if (count($validationErrors) === 0) {
            return true;
        }
        foreach ($validationErrors as $error) {
            $message = $error->getPropertyPath() . ': ' . $error->getMessage();
            $this->errorHandler->addError(400, $message, $message, $message, $message);
        }

        return false;
    }

    /**
     * @param Request $request
     * @return \Sso\WebserviceBundle\Services\User\ChangePassword\RequestData\PasswordData
     */
    private function getPaswordDTO(Request $request)
    {
        $updateUserData = $this->factory->passwordData();
        //now fill the DTO -> it's magick
        return $this->autoMapper->modelInToModelOut($request->getUser()->getChangePassword()->getValue()->getPasswordType(), $updateUserData);
    }
}
