<?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\ObjectWs\Version1\ObjectValue\Add\Utils\ObjectValueAdd;

use Sso\RestBundle\Api\Manager as ApiManager;
use GuzzleHttp\Client;
use LifeStyle\Tools\RestAuthBundle\Security\Authentication\Token\UidentifyToken;
use Sso\RestBundle\ModelRest\Request\ObjectWs\Version1\ObjectValue\Add\Item as RequestItem;
use Sso\RestBundle\ModelRest\Response\ObjectWs\Version1\ObjectValue\Add\Item as ResponseItem;
use GuzzleHttp\Exception\RequestException;

/**
 * Class Index
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\RestBundle\Worker\ObjectWs\Version1\ObjectValue\Add\Utils\ObjectValueAdd
 */
class Index
{

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

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

    /**
     * @var \Sso\RestBundle\ModelXml\Response\ObjectWs\Version1\ObjectValue\Add\Error\Response
     */
    private $errorXmlEntity;

    /**
     * @var \Sso\RestBundle\ModelXml\Response\ObjectWs\Version1\ObjectValue\Add\Success\Response
     */
    private $successXmlEntity;

    /**
     * @var Client
     */
    private $client;

    /**
     * @param ApiManager $apiM
     * @param Client $client
     */
    public function __construct(ApiManager $apiM, Client $client)
    {
        $this->apiM = $apiM;
        $this->client = $client;
        $this->userToken = $this->apiM->getContainer()->get('security.token_storage')->getToken();
    }

    /**
     * @param RequestItem $item
     * @return ResponseItem
     */
    public function send(RequestItem $item)
    {
        $requestModelXml = $this->apiM->modelXml()->request()->objectWs()->version1()->objectValue()->add()->objectValueAdd()->request();

        // add credentials
        $credentialsModelXml = $this->apiM->modelXml()->request()->objectWs()->version1()->objectValue()->add()->objectValueAdd()->credentials();
        $credentialsModelXml->setCredentialsData($this->userToken->servicetoken, 'MyService',
            $this->userToken->useridentifier, $this->userToken->username, 'en');
        $requestModelXml->setCredentials($credentialsModelXml);

        // add objectType
        $objectModelXml = $this->apiM->modelXml()->request()->objectWs()->version1()->objectValue()->add()->objectValueAdd()->objectValue();
        $objectModelXml->setObjectValueData($item->getObjectGuid(), $item->getObjectValue(), $item->getLanguageCode(),
            $item->getAttributeId());
        $requestModelXml->setObjectValue($objectModelXml);

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

        try {
            $clientResponse = $this->client->post($this->apiM->configuration()->objectWs()->getBaseUrl() . $this->apiM->configuration()->objectWs()->getServiceAction(),
                $options);
        } catch (RequestException $ex) {
            $errorResponse = $ex->getResponse()->getBody()->getContents();
            $this->apiM->logger()->error($errorResponse);

            return $this->buildItem(['status' => false, 'xml' => $errorResponse], $item);
        }

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

    /**
     * @param string $xmlResponse
     * @param RequestItem $item
     * @return ResponseItem
     */
    private function buildItem($xmlResponse, RequestItem $item)
    {
        $responseItem = $this->apiM->modelRest()->response()->objectWs()->version1()->objectValue()->add()->item();

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

        return $responseItem;
    }

    /**
     * @param string $xmlString
     * @param ResponseItem $responseItem
     * @return ResponseItem
     */
    private function buildSuccess($xmlString, ResponseItem $responseItem)
    {
        $responseItem->setCode(200);
        $responseItem->setScriptTimeSec($this->apiM->scriptTimeSeconds());
        $this->successXmlEntity = $this->apiM->serializer()->deserialize($xmlString,
            'Sso\RestBundle\ModelXml\Response\ObjectWs\Version1\ObjectValue\Add\Success\Response', 'xml');
        $responseItem = $this->apiM->helper()->mapper()->modelInToModelOut($this->successXmlEntity->getObjectValue()->getAdd()->getObjectValueType(),
            $responseItem);

        return $responseItem;
    }

    /**
     * @param string $xmlString
     * @param ResponseItem $responseItem
     * @return ResponseItem
     */
    private function buildError($xmlString, ResponseItem $responseItem)
    {
        $errorsItem = $this->apiM->modelRest()->response()->objectWs()->version1()->objectValue()->add()->errors();
        $responseItem->setCode(400);
        $this->errorXmlEntity = $this->apiM->serializer()->deserialize($xmlString,
            'Sso\RestBundle\ModelXml\Response\ObjectWs\Version1\ObjectValue\Add\Error\Response', 'xml');
        $errorsItem->setTrackId($this->errorXmlEntity->getTrackid());
        $errorsItem->setCode(400);
        $errors = $this->errorXmlEntity->getObjectValue()->getAdd()->getError();

        foreach ($errors as $error) {
            $errorItem = $this->apiM->modelRest()->response()->objectWs()->version1()->objectValue()->add()->error();
            $message = 'ErrorCode: ' . $error->getErrorCode() . ' ErrorRef: ' . $error->getErrorRef() . ' ShortMessage: ' . $error->getShortMessage();
            $errorItem->setMessage($message);
            $errorItem->setCode(400);
            $errorItem->setException('external');
            //$this->errors->addError(400, $message, 'external', $error->getLongMessage());
            $errorsItem->addError($errorItem);
        }
        $responseItem->setScriptTimeSec($this->apiM->scriptTimeSeconds());
        $responseItem->setErrors($errorsItem);

        return $responseItem;
    }
}