<?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\UserWs\Version1\Attribute\Delete;

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\UserWs\Version1\Attribute\Delete\Request as RequestModel;
use Sso\RestBundle\ModelRest\Request\UserWs\Version1\Attribute\Delete\Item as RequestItem;
use Sso\RestBundle\ModelRest\Response\UserWs\Version1\Attribute\Delete\Item as ResponseItem;
use LifeStyle\Tools\RestAuthBundle\Security\Authentication\Token\UidentifyToken;
use Symfony\Component\HttpFoundation\Request;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Client;

/**
 * Class Handler
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\RestBundle\Worker\UserWs\Version1\Attribute\Delete
 */
class Handler
{
    /**
     * @var UidentifyToken
     */
    protected $userToken;

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

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

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

    /**
     * @var \Sso\RestBundle\ModelXml\Response\UserWs\Version1\Attribute\Delete\Error\Response
     */
    protected $errorXmlAttribute;

    /**
     * @var \Sso\RestBundle\ModelXml\Response\UserWs\Version1\Attribute\Delete\Success\Response
     */
    protected $successXmlAttribute;

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

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

    /**
     * holds the complete response errors and success for every item
     * @var \Sso\RestBundle\ModelRest\Response\UserWs\Version1\Attribute\Delete\Response
     */
    protected $restResponseEntity;

    /**
     * @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->getContainer()->get('security.token_storage')->getToken();
        $this->restResponseEntity = $this->apiM->modelRest()->response()->userWs()->version1()->attribute()->delete()->response();
    }

    /**
     * @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
        foreach ($requestModelRest->getItem() as $item) {
            $responseItem = $this->send($item);

            //now add the current item to the response
            $this->restResponseEntity->addItem($responseItem);

        }

        $view = RestView::create();
        $view->setData($this->restResponseEntity)->setStatusCode(200);
        return $view;
    }

    /**
     * @param Request $request
     * @return RequestModel
     */
    private function validateRestRequest(Request $request)
    {
        // check content
        $requestContent = $request->getContent();

        if (empty($requestContent)) {
            $this->errors->addError(204, 'No Content found in your request', 'external')->setCode(204);
            return;
        }

        $this->format = preg_match('/\.xml/i', $request->getUri()) ? 'xml' : 'json';

        //no validate the content
        if ($this->format == "xml") {
            $errors = $this->apiM->helper()->string()->validateXML($requestContent);
        } else {
            $errors = $this->apiM->helper()->string()->validateJson($requestContent);
        }
        // collect errors
        foreach ($errors as $error) {
            $this->errors->addError(400, $error, 'external', 'InvalidRequest')->setCode(400);
            return;
        }

        //now build request model
        $requestModel = $this->apiM->serializer()->deserialize($requestContent,
            'Sso\RestBundle\ModelRest\Request\UserWs\Version1\Attribute\Delete\Request', $this->format);

        $validationErrors = $this->apiM->validator()->validate($requestModel);

        if (count($validationErrors) > 0) {
            foreach ($validationErrors as $error) {
                $message = $error->getPropertyPath() . ": " . $error->getMessage();
                $this->errors->addError(400, $message, 'external')->setCode(400);
            }
        }

        return $requestModel;
    }

    /**
     * @param RequestItem $item
     * @return ResponseItem
     */
    public function send(RequestItem $item)
    {
        $requestModelXml = $this->apiM->modelXml()->request()->userWs()->version1()->attribute()->delete()->request();

        // add credentials
        $credentialsModelXml = $this->apiM->modelXml()->request()->userWs()->version1()->attribute()->delete()->credentials();
        $credentialsModelXml->setCredentialsData($this->userToken->servicetoken, 'AttributeDelete',
            $this->userToken->useridentifier, $this->userToken->username, 'en');
        $requestModelXml->setCredentials($credentialsModelXml);

        // add attributeType
        $attributeModelXml = $this->apiM->modelXml()->request()->userWs()->version1()->attribute()->delete()->attribute();
        $attributeModelXml->setAttributeTypeData($item->getId(), $item->isDeleteReferences());
        $requestModelXml->setAttribute($attributeModelXml);

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

        try {
            $clientResponse = $this->client->post($this->apiM->configuration()->userWs()->getBaseUrl() . $this->apiM->configuration()->userWs()->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 $requestItem
     * @return ResponseItem
     */
    private function buildItem($xmlResponse, RequestItem $requestItem)
    {
        $responseItem = $this->apiM->modelRest()->response()->userWs()->version1()->attribute()->delete()->item();
        $responseItem->setId($requestItem->getId());

        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->successXmlAttribute = $this->apiM->serializer()->deserialize($xmlString,
            'Sso\RestBundle\ModelXml\Response\UserWs\Version1\Attribute\Delete\Success\Response', 'xml');

        $responseItem->setId($this->successXmlAttribute->getAttribute()->getShow()->getAttributeType()->getId());
        $responseItem->setTrackId($this->successXmlAttribute->getTrackid());


        return $responseItem;
    }

    /**
     * @param string $xmlString
     * @param ResponseItem $responseItem
     * @return ResponseItem
     */
    private function buildError($xmlString, ResponseItem $responseItem)
    {
        $errorsItem = $this->apiM->modelRest()->response()->userWs()->version1()->attribute()->delete()->errors();
        $responseItem->setCode(400);

        $this->errorXmlAttribute = $this->apiM->serializer()->deserialize($xmlString,
            'Sso\RestBundle\ModelXml\Response\UserWs\Version1\Attribute\Delete\Error\Response', 'xml');

        $errorsItem->setTrackId($this->errorXmlAttribute->getTrackid());
        $errorsItem->setCode(400);

        $errors = $this->errorXmlAttribute->getAttribute()->getShow()->getError();

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

        return $responseItem;
    }

}
