<?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\AttributeGroup\Update;

use Sso\RestBundle\Api\ExceptionCollection\MainValidationException;
use Sso\RestBundle\Api\Manager as ApiManager;
use Sso\RestBundle\ModelRest\Request\ObjectWs\Version1\AttributeGroup\Update\AttributeGroup as RequestAttributeGroup;
use Sso\RestBundle\ModelRest\Request\ObjectWs\Version1\AttributeGroup\Update\Request as RequestModel;
use Sso\RestBundle\ModelRest\Response\ObjectWs\Version1\AttributeGroup\Update\AttributeGroup as ResponseAttributeGroup;
use Sso\RestBundle\ModelRest\Response\ObjectWs\Version1\AttributeGroup\Update\Response as ResponseModel;
use Sso\RestBundle\ModelXml\Response\ObjectWs\Version1\AttributeGroup\Update\Error\Response as ErrorXMLResponse;
use Sso\RestBundle\ModelXml\Response\ObjectWs\Version1\AttributeGroup\Update\Success\Response as SuccessXMLResponse;
use FOS\RestBundle\View\View as RestView;
use GuzzleHttp\Client;
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
 * @package Sso\RestBundle\Worker\ObjectWs\Version1\AttributeGroup\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 ResponseModel
     */
    private $restResponseModel;

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

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

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

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

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

    /**
     * @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->getToken();
        $this->restResponseModel = $this->apiM->modelRest()->response()->objectWs()->version1()->attributeGroup()->update()->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);

        // second: send data to object ws AttributeGroupAdd
        foreach ($requestModelRest->getAttributeGroups() as $attributeGroup) {
            $responseAttributeGroup = $this->send($attributeGroup);

            //now add the current item to the response
            $this->restResponseModel->addAttributeGroup($responseAttributeGroup);
        }

        $this->restResponseModel->setCode($this->oneResponseSuccess ? 200 : 400);
        $this->restResponseModel->setTrackId($this->apiM->trackId());
        $this->restResponseModel->setScriptTimeSec($this->apiM->scriptTimeSeconds());

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

    /**
     * @param RequestAttributeGroup $attributeGroup
     *
     * @return ResponseAttributeGroup
     */
    public function send(RequestAttributeGroup $attributeGroup)
    {
        $requestModelXml = $this->apiM->modelXml()->request()->objectWs()->version1()->attributeGroup()->update()->request();

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

        // add objectType
        $objectModelXml = $this->apiM->modelXml()->request()->objectWs()->version1()->attributeGroup()->update()->attributeGroup();

        $objectModelXml->setAttributeGroupData(
            $attributeGroup->getId(),
            $attributeGroup->getName(),
            $attributeGroup->getAdd(),
            $attributeGroup->getDelete(),
            $attributeGroup->isDeleteReferences()
        );

        $requestModelXml->setAttributeGroup($objectModelXml);

        try {
            $clientResponse = $this->apiM->client()->post(
                $this->apiM->configuration()->objectWs()->getBaseUrl() . $this->apiM->configuration()->userWs()->getServiceAction(),
                $this->apiM->clientHelper()->options()->getOptions(1, 'AttributeGroup', 'Update',
                    $this->apiM->serializer()->serialize($requestModelXml, 'xml'))
            );
        } catch (RequestException $ex) {
            $errorResponse = $ex->getResponse()->getBody()->getContents();
            $this->apiM->logger()->error($errorResponse);

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

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

    /**
     * @param string $xmlResponse
     * @param RequestAttributeGroup $attributeGroup
     *
     * @return ResponseAttributeGroup
     */
    private function buildItem($xmlResponse, RequestAttributeGroup $attributeGroup)
    {
        $responseAttributeGroup = $this->apiM->modelRest()->response()->objectWs()->version1()->attributeGroup()->update()->attributeGroup();
        $responseAttributeGroup
            ->setId($attributeGroup->getId())
            ->setName($attributeGroup->getName());

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

        return $responseAttributeGroup;
    }

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

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

        $this->oneResponseSuccess = true;

        /**
         * @var ResponseAttributeGroup $responseAttributeGroup
         */
        $responseAttributeGroup = $this->apiM->helper()->mapper()->modelInToModelOut(
            $this->successXmlEntity->getAttributeGroup()->getUpdate()->getAttributeGroupType(),
            $responseAttributeGroup
        );

        // 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
        $responseAttributeGroup->setCode(200);

        return $responseAttributeGroup;
    }

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

        foreach ($errors as $error) {
            $errorItem = $this->apiM->modelRest()->response()->objectWs()->version1()->attributeGroup()->update()->error();
            $message = 'ErrorCode: ' . $error->getErrorCode() . ' ErrorRef: ' . $error->getErrorRef() . ' ShortMessage: ' . $error->getShortMessage();
            $errorItem->setMessage($message);
            $errorItem->setCode(400);
            $errorItem->setException(static::ERROR_EXTERNAL);
            $responseAttributeGroup->addError($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 user response
        $responseAttributeGroup->setCode(400);

        return $responseAttributeGroup;
    }
}
