<?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\Language\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\Language\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\Language\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\Language\Show\Error\Response
     */
    protected $errorXmlObject;

    /**
     * @var \Sso\RestBundle\ModelXml\Response\ObjectWs\Version1\Language\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 = $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 LanguageGet
        $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()->language()->show();

        $restRequestModel
            ->setCode($request->query->get('code'));

        $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\Language\Show\Success\Response', 'xml');
        $modelRestResponse = $this->apiM->modelRest()->response()->objectWs()->version1()->language()->show()->success()->response();

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

        // map and set language type models
        $xmlAttrTypes = $this->successXmlObject->getLanguage()->getShow()->getLanguageType();
        foreach ($xmlAttrTypes as $attrType) {
            $mappedModel = $this->apiM->helper()->mapper()->modelInToModelOut($attrType,
                $this->apiM->modelRest()->response()->objectWs()->version1()->language()->show()->success()->languageType());
            $modelRestResponse->addLanguage($mappedModel);
        }

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

        return $view;
    }

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

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

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

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

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


        $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()->language()->show()->request();

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

        // add objecttype
        $languageModelXml = $this->apiM->modelXml()->request()->objectWs()->version1()->language()->show()->language();
        $languageModelXml->setLanguageTypeData($request->getCode());
        $requestModelXml->setLanguage($languageModelXml);

        $options = array(
            'headers' => array(
                'API-VERSION' => '1',
                'API-CONTROLLER' => 'Language',
                '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()];
    }

}
