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

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

/**
 * Class Handler
 * @package Sso\RestBundle\Worker\ObjectWs\Version1\AttributeGroup\Show
 */
class Handler
{
    /**
     * @var UidentifyToken
     */
    protected $userToken;

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

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

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

    /**
     * @var \Sso\RestBundle\ModelXml\Response\ObjectWs\Version1\AttributeGroup\Show\Error\Response
     */
    protected $errorXmlObject;

    /**
     * @var \Sso\RestBundle\ModelXml\Response\ObjectWs\Version1\AttributeGroup\Show\Success\Response
     */
    protected $successXmlObject;

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

    /**
     * @var Client
     */
    protected $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();
    }

    /**
     * @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 object ws AttributeGroupGet
        $resModelXmlArray = $this->send($requestModelRest);

        // third: build response
        if ($resModelXmlArray['status']) {
            //ok
            $view = $this->buildSuccessView($resModelXmlArray['xml']);
        } else {
            //error
            $view = $this->buildErrorView($resModelXmlArray['xml']);
        }

        return $view;
    }

    /**
     * @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()->objectWs()->version1()->attributeGroup()->show();

        $restRequestModel
            ->setId($request->query->get('id'))
            ->setOffset($request->query->get('offset'))
            ->setLimit($request->query->get('limit'));

        $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 string $xmlString
     * @return RestView
     */
    private function buildSuccessView($xmlString)
    {
        $this->successXmlObject = $this->apiM->serializer()->deserialize($xmlString,
            'Sso\RestBundle\ModelXml\Response\ObjectWs\Version1\AttributeGroup\Show\Success\Response', 'xml');
        $modelRestResponse = $this->apiM->modelRest()->response()->objectWs()->version1()->attributeGroup()->show()->success()->response();

        $modelRestResponse = $this->apiM->helper()->mapper()->modelInToModelOut($this->successXmlObject,
            $modelRestResponse);
        $modelRestResponse->setCode(200);
        $modelRestResponse->setCount($this->successXmlObject->getAttributeGroup()->getShow()->getCount());
        $modelRestResponse->setOffset($this->successXmlObject->getAttributeGroup()->getShow()->getOffset());
        $modelRestResponse->setLimit($this->successXmlObject->getAttributeGroup()->getShow()->getLimit());

        // map and set attributeGroup type models
        $xmlAttrTypes = $this->successXmlObject->getAttributeGroup()->getShow()->getAttributeGroupType();
        foreach ($xmlAttrTypes as $attrType) {
            $mappedModel = $this->apiM->helper()->mapper()->modelInToModelOut($attrType,
                $this->apiM->modelRest()->response()->objectWs()->version1()->attributeGroup()->show()->success()->attributeGroupType($this->apiM->helper()->mapper()));
            $modelRestResponse->addAttributeGroup($mappedModel);
        }

        $view = RestView::create();
        $modelRestResponse->setScriptSeconds($this->apiM->scriptTimeSeconds());
        $view->setData($modelRestResponse);
        $view->setStatusCode(200);

        return $view;
    }

    /**
     * @param string $xmlString
     * @return RestView
     */
    private function buildErrorView($xmlString)
    {
        $responseItem = $this->apiM->modelRest()->response()->objectWs()->version1()->attributeGroup()->show()->error()->response();

        $this->errorXmlObject = $this->apiM->serializer()->deserialize($xmlString,
            'Sso\RestBundle\ModelXml\Response\ObjectWs\Version1\AttributeGroup\Show\Error\Response', 'xml');

        $responseItem->setTrackId($this->errorXmlObject->getTrackid());
        $responseItem->setScriptSeconds($this->apiM->scriptTimeSeconds());
        $responseItem->setCode(400);

        $errors = $this->errorXmlObject->getAttributeGroup()->getShow()->getError();

        foreach ($errors as $error) {
            $errorItem = $this->apiM->modelRest()->response()->objectWs()->version1()->attributeGroup()->show()->error()->error();
            $message = 'ErrorCode: ' . $error->getErrorCode() . ' ErrorRef: ' . $error->getErrorRef() . ' ShortMessage: ' . $error->getShortMessage();
            $errorItem->setMessage($message);
            $errorItem->setCode(400);
            $errorItem->setException('external');
            $responseItem->addError($errorItem);
        }

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

        return $view;
    }

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

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

        // add objecttype
        $attrGroupModelXml = $this->apiM->modelXml()->request()->objectWs()->version1()->attributeGroup()->show()->attributeGroup();
        $attrGroupModelXml->setAttributeGroupTypeData($request->getId(), $request->getOffset(), $request->getLimit());
        $requestModelXml->setAttributeGroup($attrGroupModelXml);

        $options = array(
            'headers' => array(
                'API-VERSION' => '1',
                'API-CONTROLLER' => 'AttributeGroup',
                'API-ACTION' => 'Show',
                '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 ['status' => false, 'xml' => $errorResponse];
        }

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

}
