<?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\RestBundle\Worker\UserWs\Version2\User\Update;

use Sso\RestBundle\Api\ExceptionCollection\MainValidationException;
use Sso\RestBundle\Api\Manager as ApiManager;
use GuzzleHttp\Exception\RequestException;
use LifeStyle\Tools\RestErrorBundle\Api\Manager as ErrorApi;
use LifeStyle\Tools\RestErrorBundle\Api\Error\Errors\Index as Errors;
use LifeStyle\Tools\RestAuthBundle\Security\Authentication\Token\UidentifyToken;
use Symfony\Component\HttpFoundation\Request;
use Sso\RestBundle\ModelRest\Request\UserWs\Version2\User\Update\Request as RequestModel;
use Sso\RestBundle\ModelRest\Request\UserWs\Version2\User\Update\UserType as RequestUserType;
use Sso\RestBundle\ModelRest\Response\UserWs\Version2\User\Update\UserType as ResponseUserType;
use Sso\RestBundle\ModelRest\Response\UserWs\Version2\User\Update\Response as RestResponseModel;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\User\Update\Success\Response as SuccessXMLResponse;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\User\Update\Error\Response as ErrorXMLResponse;

/**
 * Class Handler
 * @package Sso\RestBundle\Worker\UserWs\Version2\User\Update
 */
class Handler
{
    const STATUS = "status";
    const ERROR_EXTERNAL = "external";

    /**
     * @var UidentifyToken
     */
    private $userToken;

    /**
     * @var ApiManager
     */
    private $apiM;

    /**
     * @var ErrorApi
     */
    private $errorApi;

    /**
     * @var Errors
     */
    private $errors;

    /**
     * @var ErrorXMLResponse
     */
    private $errorXmlEntity;

    /**
     * @var SuccessXMLResponse
     */
    private $successXmlEntity;

    /**
     * @var RestResponseModel
     */
    private $restResponseModel;

    /**
     * @var bool
     */
    private $oneResponseSuccess = false;

    /**
     * @param ApiManager $apiM
     */
    public function __construct(ApiManager $apiM)
    {
        $this->apiM = $apiM;
        $this->errorApi = $this->apiM->errorManager();
        $this->errors = $this->errorApi->error()->errors();
        $this->restResponseModel = $this->apiM->modelRest()->response()->userWs()->version2()->user()->update()->response();
        $this->userToken = $this->apiM->getToken();
    }

    public function init(Request $request)
    {
        // first: validate main if there is any error it is allowed to use the default error response
        try {
            list($requestContent, $format) = $this->apiM->mainValidator()->validateRestRequest($request);
        } catch (MainValidationException $exc) {
            $this->errorApi->error()->errors()->setScriptSeconds($this->apiM->scriptTimeSeconds());

            return $this->errorApi->error()->view()->getErrorsView($this->errors->getErrors(), 416);
        }

        // second: setting the request model
        $requestModelRest = $this->apiM->serializer()->deserialize($requestContent, RequestModel::class, $format);

        // loop the user type
        foreach ($requestModelRest->getUserType() as $userType) {
            $responseUserType = $this->sendXmlRequest($userType, $request->get('guid', null));
            $this->restResponseModel->addUserType($responseUserType);
        }

        // reset the main code status
        $this->restResponseModel->setCode($this->oneResponseSuccess ? 200 : 400);

        return $this->apiM->restView()->setData($this->restResponseModel)->setStatusCode($this->oneResponseSuccess ? 200 : 400);
    }

    private function sendXmlRequest(RequestUserType $requestModelRest, $userGuid)
    {
        $requestModel = $this->apiM->modelXml()->request()->userWs()->version2()->user()->update()->request();

        // add credentials
        $credentialsModelXml = $this->apiM->modelXml()->request()->userWs()->version2()->user()->update()->credentials();
        $credentialsModelXml->setCredentialsData(
            $this->userToken->servicetoken,
            'User',
            $this->userToken->useridentifier,
            $this->userToken->username,
            'en'
        );
        $requestModel->setCredentials($credentialsModelXml);

        // add user data
        $objectModelXml = $this->apiM->modelXml()->request()->userWs()->version2()->user()->update()->user();
        $objectModelXml->setUserData(
            $requestModelRest->getEmail(),
            $requestModelRest->getUsername(),
            $requestModelRest->getFirstName(),
            $requestModelRest->getLastName(),
            $requestModelRest->getActive(),
            $requestModelRest->getAuthId(),
            $requestModelRest->getLdapSearchAttributes(),
            $requestModelRest->getLdapSearchValue(),
            $requestModelRest->getMfaEnabled(),
            $requestModelRest->getMfaRecreate()
        );
        $requestModel->setUser($objectModelXml);

        // set user key
        $userKeyType = $this->apiM->modelXml()->request()->userWs()->version2()->user()->update()->userKeyType();

        if ($requestModelRest->getKeyType() !== null) {
            $userKeyType->setIdentifier($requestModelRest->getKeyType()->getIdentifier());
        } elseif ((null !== $userGuid) && strlen($userGuid) > 0) {
            $userKeyType->setIdentifier($userGuid);
        } else {
            $userKeyType->setIdentifier($requestModelRest->getUsername());
        }

        $key = $this->apiM->modelXml()->request()->userWs()->version2()->user()->update()->key();
        $key->setUserKeyType($userKeyType);
        $objectModelXml->getUpdate()->setKey($key);

        // send request
        try {
            $clientResponse = $this->apiM->client()->post(
                $this->apiM->configuration()->userWs()->getBaseUrl() . $this->apiM->configuration()->userWs()->getServiceAction(),
                $this->apiM->clientHelper()->options()->getOptions(
                    2,
                    'User',
                    'Update',
                    $this->apiM->serializer()->serialize($requestModel, 'xml'))
            );
        } catch (RequestException $ex) {
            $errorResponse = $ex->getResponse()->getBody()->getContents();
            $this->apiM->logger()->error($errorResponse);
            return $this->buildItem([static::STATUS => false, 'xml' => $errorResponse]);
        }

        return $this->buildItem([static::STATUS => true, 'xml' => $clientResponse->getBody()->getContents()]);
    }

    /**
     *
     * @param string $xmlResponse
     * @return ResponseUserType
     */
    private function buildItem($xmlResponse)
    {
        $responseItem = $this->apiM->modelRest()->response()->userWs()->version2()->user()->update()->userType();

        if (!$xmlResponse[static::STATUS]) {
            // build error response for a userType
            $view = $this->buildError($xmlResponse['xml'], $responseItem);
        } else {
            // fill the success response for a userType
            $view = $this->buildSuccess($xmlResponse['xml'], $responseItem);
        }

        return $view;
    }

    /**
     *
     * @param string $xmlString
     * @param ResponseUserType $responseItem
     * @return ResponseUserType
     */
    private function buildSuccess($xmlString, ResponseUserType $responseItem)
    {
        $this->successXmlEntity = $this->apiM->serializer()->deserialize($xmlString, SuccessXMLResponse::class, 'xml');

        if (!$this->successXmlEntity->getUser()
            || ($this->successXmlEntity->getUser()
                && $this->successXmlEntity->getUser()->getUpdate()->getStatus() != 'Success')
        ) {
            return $this->buildError($xmlString, $responseItem);
        }

        $this->oneResponseSuccess = true;

        /**
         * @var ResponseUserType $responseItem
         */
        $responseItem = $this->apiM->helper()->mapper()->modelInToModelOut(
            $this->successXmlEntity->getUser()->getUpdate()->getUserType(),
            $responseItem
        );

        // Add additional fields to response
        $this->restResponseModel
            ->setCode($this->successXmlEntity->getCode())
            ->setTrackId($this->successXmlEntity->getTrackId())
            ->setDate($this->successXmlEntity->getDate())
            ->setScriptTimeSec($this->successXmlEntity->getScriptTimeSec());

        // Add additional fields to response user
        $responseItem->setCode(200);

        return $responseItem;
    }

    /**
     * @param ResponseUserType $responseItem
     * @param string $xmlString
     * @return ResponseUserType
     */
    private function buildError($xmlString, ResponseUserType $responseItem)
    {
        $this->errorXmlEntity = $this->apiM->serializer()->deserialize($xmlString, ErrorXMLResponse::class, 'xml');
        $errors = $this->errorXmlEntity->getErrors();

        foreach ($errors as $error) {
            $errorItem = $this->apiM->modelRest()->response()->userWs()->version2()->user()->update()->error();
            $message = 'ErrorCode: ' . $error->getErrorCode() . ' ErrorRef: ' . $error->getErrorRef() . ' ShortMessage: ' . $error->getShortMessage();
            $errorItem->setMessage($message);
            $errorItem->setCode(400);
            $errorItem->setException(static::ERROR_EXTERNAL);
            $responseItem->setError($errorItem);
        }

        // Add additional fields to response
        $this->restResponseModel
            ->setCode(400)
            ->setTrackId($this->errorXmlEntity->getTrackId())
            ->setDate($this->errorXmlEntity->getDate())
            ->setScriptTimeSec($this->apiM->scriptTimeSeconds());

        // Add additional fields to response
        $responseItem->setCode($this->errorXmlEntity->getCode());

        return $responseItem;
    }
}
