<?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\Version1\UserService\ActivateRequest;

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

/**
 * Class Handler
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\RestBundle\Worker\UserWs\Version1\UserService\ActivateRequest
 */
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 bool
     */
    private $oneResponseSuccess = false;

    /**
     * holds the complete response errors and success for every item
     * @var \Sso\RestBundle\ModelRest\Response\UserWs\Version1\UserApplication\Delete\Response
     */
    protected $restResponseModel;

    /**
     * @param ApiManager $apiM
     */
    public function __construct(ApiManager $apiM)
    {
        $this->apiM = $apiM;
        $this->client = $this->apiM->client();
        $this->errorApi = $this->apiM->errorManager();
        $this->errors = $this->errorApi->error()->errors();
        $this->format = 'json';
        $this->userToken = $this->apiM->getContainer()->get('security.token_storage')->getToken();
        $this->restResponseModel = $this->apiM->modelRest()->response()->userWs()->version1()->userService()->activateRequest()->response();
    }

    /**
     * @param Request $request
     * @return RestView
     */
    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
        /** @var RequestModel $requestModelRest */
        $requestModelRest = $this->apiM->serializer()->deserialize($requestContent, RequestModel::class, $format);

        if ($this->errors->hasErrors()) {
            return $this->errorApi->error()->view()->getErrorsView($this->errors->getErrors());
        }

        // second: send data to user ws
        foreach ($requestModelRest->getUserTypes() as $userType) {
            $responseUserType = $this->send($userType);
            // now add the current item to the response
            $this->restResponseModel->addUserType($responseUserType);
        }
        $responseCode = $this->oneResponseSuccess ? 200 : 400;
        $this->restResponseModel->setCode($responseCode);

        $view = RestView::create();
        $view->setData($this->restResponseModel)->setStatusCode($responseCode);

        return $view;
    }

    /**
     * @param RequestUserType $requestUserType
     * @return ResponseUserType
     */
    public function send(RequestUserType $requestUserType)
    {
        $requestModelXml = $this->apiM->modelXml()->request()->userWs()->version1()->userService()->activateRequest()->request();

        // add credentials
        $credentialsModelXml = $this->apiM->modelXml()->request()->userWs()->version1()->userService()->activateRequest()->credentials();
        $credentialsModelXml->setCredentialsData($this->userToken->servicetoken, 'UserServiceActivateRequest',
            $this->userToken->useridentifier, $this->userToken->username, 'en');
        $requestModelXml->setCredentials($credentialsModelXml);

        // add userApplicationType
        $userServiceModelXml = $this->apiM->modelXml()->request()->userWs()->version1()->userService()->activateRequest()->userService();
        $userServiceModelXml->setUserServiceData($requestUserType->getIdentifier());
        $requestModelXml->setUserService($userServiceModelXml);

        // send request
        try {
            $clientResponse = $this->apiM->client()->post(
                $this->apiM->configuration()->userWs()->getBaseUrl() . $this->apiM->configuration()->userWs()->getServiceAction(),
                $this->apiM->clientHelper()->options()->getOptions(1, 'UserService', 'ActivateRequest',
                    $this->apiM->serializer()->serialize($requestModelXml, '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)
    {
        $responseUserType = $this->apiM->modelRest()->response()->userWs()->version1()->userService()->activateRequest()->userType();

        if (!$xmlResponse[static::STATUS]) {
            return $this->buildError($xmlResponse['xml'], $responseUserType);
        }

        return $this->buildSuccess($xmlResponse['xml'], $responseUserType);
    }

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

        if (!$this->successXmlEntity->getUserService()
            || ($this->successXmlEntity->getUserService()
                && $this->successXmlEntity->getUserService()->getActivateRequest()->getStatus() != 'Success')
        ) {
            return $this->buildError($xmlString, $responseUserType);
        }

        $this->oneResponseSuccess = true;

        /** @var ResponseUserType $responseUserType */
        $responseUserType = $this->apiM->helper()->mapper()->modelInToModelOut(
            $this->successXmlEntity->getUserService()->getActivateRequest()->getUserType(),
            $responseUserType
        );

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

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

        return $responseUserType;
    }

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

        foreach ($errors as $error) {
            $errorItem = $this->apiM->modelRest()->response()->userWs()->version1()->userService()->activateRequest()->error();
            $message = 'ErrorCode: ' . $error->getErrorCode() . ' ErrorRef: ' . $error->getErrorRef() . ' ShortMessage: ' . $error->getShortMessage();
            $errorItem->setMessage($message);
            $errorItem->setCode(400);
            $errorItem->setException(static::ERROR_EXTERNAL);
            $responseUserType->addError($errorItem);
        }

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

        // Add additional fields to error response
        $responseUserType->setCode(400);

        return $responseUserType;
    }
}
