<?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\UserApplicationAttribute\Show;

use FOS\RestBundle\View\View as RestView;
use Sso\RestBundle\Api\Manager as ApiManager;
use LifeStyle\Tools\RestErrorBundle\Api as ErrorApi;
use LifeStyle\Tools\RestErrorBundle\Api\Error\Errors\Index as Errors;
use GuzzleHttp\Exception\RequestException;
use LifeStyle\Tools\RestAuthBundle\Security\Authentication\Token\UidentifyToken;
use Sso\RestBundle\ModelRest\Request\UserWs\Version1\UserApplicationAttribute\Show\Request as RequestModel;
use Sso\RestBundle\ModelRest\Response\UserWs\Version1\UserApplicationAttribute\Show\Item as ResponseItem;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class Handler
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\RestBundle\Worker\UserWs\Version1\UserApplicationAttribute\Show
 */
class Handler
{
    /**
     * @var UidentifyToken
     */
    protected $userToken;

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

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

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

    /**
     * @var \Sso\RestBundle\ModelXml\Response\UserWs\Version1\UserApplicationAttribute\Show\Error\Response
     */
    protected $errorXmlEntity;

    /**
     * @var \Sso\RestBundle\ModelXml\Response\UserWs\Version1\UserApplicationAttribute\Show\Success\Response
     */
    protected $successXmlEntity;

    /**
     * @var string
     */
    protected $format;

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

    /**
     * @param Request $request
     * @return RestView
     */
    public function init(Request $request)
    {
        // first: validate input data
        $requestModelRest = $this->validateRestRequest($request);
        if ($this->errors->hasErrors()) {
            return $this->errorApi->error()->view()->getErrorsView($this->errors->getErrors());
        }

        // second: send data to xml ws and return created view
        return $this->sendXmlRequest($requestModelRest);
    }

    /**
     * @param Request $request
     * @return RequestModel
     */
    private function validateRestRequest(Request $request)
    {
        $this->format = preg_match('/\.xml/i', $request->getUri()) ? 'xml' : 'json';

        $restRequestModel = $this->apiM->modelRest()->request()->userWs()->version1()->userApplicationAttribute()->show();

        $restRequestModel
            ->setIdentifier($request->query->get('identifier'))
            ->setApplicationName($request->query->get('applicationName'));

        $validationErrors = $this->apiM->validator()->validate($restRequestModel);

        if (count($validationErrors) > 0) {
            foreach ($validationErrors as $error) {
                $message = $error->getPropertyPath() . ": " . $error->getMessage();
                $this->errors->addError(400, $message, 'external')->setCode(400);
            }
        }

        return $restRequestModel;
    }

    /**
     * @param RequestModel $requestModelRest
     * @return RestView
     */
    private function sendXmlRequest(RequestModel $requestModelRest)
    {
        $requestModel = $this->apiM->modelXml()->request()->userWs()->version1()->userApplicationAttribute()->show()->request();
        $userModelXml = $this->apiM->modelXml()->request()->userWs()->version1()->userApplicationAttribute()->show()->userApplicationAttribute($requestModelRest->getIdentifier(),
            $requestModelRest->getApplicationName());
        $requestModel->setUserApplicationAttribute($userModelXml);

        // add credentials
        $credentialsModelXml = $this->apiM->modelXml()->request()->userWs()->version1()->userApplicationAttribute()->show()->credentials();
        $credentialsModelXml->setCredentialsData($this->userToken->servicetoken, 'UserApplicationAttributeShow',
            $this->userToken->useridentifier, $this->userToken->username, 'en');
        $requestModel->setCredentials($credentialsModelXml);

        $options = array(
            'headers' => array(
                'API-VERSION' => '1',
                'API-CONTROLLER' => 'UserApplicationAttribute',
                'API-ACTION' => 'Show',
                'Content-Type' => 'text/xml; charset=UTF-8',
            ),
            'body' => $this->apiM->serializer()->serialize($requestModel, 'xml'),
        );

        try {
            $clientResponse = $this->apiM->client()->post($this->apiM->configuration()->userWs()->getBaseUrl() . $this->apiM->configuration()->userWs()->getServiceAction(),
                $options);
        } catch (RequestException $ex) {
            $errorResponse = $ex->getResponse()->getBody()->getContents();
            $this->apiM->logger()->error($errorResponse);
            return $this->buildItem(['status' => false, 'xml' => $errorResponse]);
        }

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


    /**
     * @param string $xmlResponse
     * @return RestView
     */
    private function buildItem($xmlResponse)
    {
        $responseItem = $this->apiM->modelRest()->response()->userWs()->version1()->userApplicationAttribute()->show()->item();

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

        return $view;
    }

    /**
     * @param string $xmlString
     * @param ResponseItem $responseItem
     * @return RestView
     */
    private function buildSuccess($xmlString, ResponseItem $responseItem)
    {
        $this->successXmlEntity = $this->apiM->serializer()->deserialize($xmlString,
            'Sso\RestBundle\ModelXml\Response\UserWs\Version1\UserApplicationAttribute\Show\Success\Response',
            'xml');

        if ($this->successXmlEntity->getStatus() != 'Success') {
            return $this->buildError($xmlString);
        }

        /**
         * @var ResponseItem $responseItem
         */
        $responseItem = $this->apiM->helper()->mapper()->modelInToModelOut($this->successXmlEntity, $responseItem);
        $responseItem->setCode(200);

        foreach ($this->successXmlEntity->getUserApplicationAttribute()->getShow()->getAttributeTypes() as $attributeType) {
            $attribute = $this->apiM->modelRest()->response()->userWs()->version1()->userApplicationAttribute()->show()->attributeType();
            $attribute
                ->setType($attributeType->getType())
                ->setName($attributeType->getName())
                ->setValue($attributeType->getValue());
            $responseItem->addAttributeType($attribute);
        }

        $view = RestView::create();
        $view->setData($responseItem)->setStatusCode(200);

        return $view;
    }

    /**
     * @param string $xmlString
     * @return RestView
     */
    private function buildError($xmlString)
    {
        $this->errorXmlEntity = $this->apiM->serializer()->deserialize($xmlString,
            'Sso\RestBundle\ModelXml\Response\UserWs\Version1\UserApplicationAttribute\Show\Error\Response', 'xml');
        $errors = $this->errorXmlEntity->getUserApplicationAttribute()->getShow()->getErrors();
        $this->errors->setCode(400);
        $this->errors->setTrackId($this->errorXmlEntity->getTrackid());
        foreach ($errors as $error) {
            $message = 'ErrorCode: ' . $error->getErrorCode() . ' ErrorRef: ' . $error->getErrorRef() . ' ShortMessage: ' . $error->getShortMessage();
            $this->errors->addError(400, $message, 'external', $error->getLongMessage());
        }

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