<?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\ObjectType\Add\Utils\ObjectTypeAdd;

use Sso\RestBundle\Api\Manager as ApiManager;
use LifeStyle\Tools\RestAuthBundle\Security\Authentication\Token\UidentifyToken;
use Sso\RestBundle\ModelRest\Request\ObjectWs\Version1\ObjectType\Add\Item as RequestItem;
use Sso\RestBundle\ModelRest\Response\ObjectWs\Version1\ObjectType\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\ObjectType\Add\Utils\ObjectTypeAdd
 */
class Index
{
    /**
     * @var UidentifyToken
     */
    protected $userToken;

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

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

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

    /**
     * @var \Sso\RestBundle\ModelXml\Response\ObjectType\Add\ObjectTypeAdd\Error\Response
     */
    protected $errorXmlEntity;

    /**
     * @var \Sso\RestBundle\ModelXml\Response\ObjectType\Add\ObjectTypeAdd\Success\Response
     */
    protected $successXmlEntity;

    /**
     * @param ApiManager $apiM
     */
    public function __construct(ApiManager $apiM)
    {
        $this->apiM = $apiM;
        $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()->objectType()->add()->objectTypeAdd()->request();

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

        // add objecttype
        $objectModelXml = $this->apiM->modelXml()->request()->objectWs()->version1()->objectType()->add()->objectTypeAdd()->objectType();
        $objectModelXml->setObjectTypeData($item->getName(), $item->getOrder());
        $requestModelXml->setObjectType($objectModelXml);

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

        try {
            $clientResponse = $this->apiM->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()->objectType()->add()->item();
        $responseItem->setName($item->getName());
        $responseItem->setOrder($item->getOrder());

        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);
        $this->successXmlEntity = $this->apiM->serializer()->deserialize($xmlString,
            'Sso\RestBundle\ModelXml\Response\ObjectWs\Version1\ObjectType\Add\ObjectTypeAdd\Success\Response',
            'xml');
        $responseItem->setName($this->successXmlEntity->getType()->getAdd()->getTypeType()->getName());
        $responseItem->setOrder($this->successXmlEntity->getType()->getAdd()->getTypeType()->getOrder());
        $responseItem->setCreated($this->successXmlEntity->getType()->getAdd()->getTypeType()->getCreated());
        $responseItem->setScriptTimeSec($this->apiM->scriptTimeSeconds());

        return $responseItem;
    }

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

        foreach ($errors as $error) {
            $errorItem = $this->apiM->modelRest()->response()->objectWs()->version1()->objectType()->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;
    }

}
