<?php

/**
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected 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  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\RestBundle\Tests\ModelRest\Response\ObjectWs\Version1\ObjectValue\Update;

use Sso\RestBundle\Api;
use Sso\RestBundle\ModelRest\Response\ObjectWs\Version1\ObjectValue\Update\Error;
use Sso\RestBundle\ModelRest\Response\ObjectWs\Version1\ObjectValue\Update\Response as RestResponse;
use Sso\RestBundle\ModelRest\Response\ObjectWs\Version1\ObjectValue\Update\ObjectValueType;
use GuzzleHttp\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Faker\Factory as FakerFactory;
use Faker\Generator as FakerGenerator;

/**
 * ResponseTest
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */
class ResponseTest extends WebTestCase
{
    /**
     * @var Api\Manager
     */
    public $apiM;

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

    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var \JMS\Serializer\Serializer
     */
    protected $serializer;

    /**
     * @var FakerGenerator
     */
    private $faker;

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

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

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

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

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

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

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

    protected function setUp()
    {
        $this->client = static::createClient();
        $this->container = $this->client->getContainer();
        $this->apiM = new Api\Manager($this->container);
        $this->serializer = $this->apiM->serializer();
        $this->faker = FakerFactory::create();

        // Set same random data
        $this->trackId = $this->faker->md5;
        $this->scriptTimeSec = $this->faker->randomFloat(2);
        $this->date = '2099-01-01T00:00:00+00:00';
        $this->message = $this->faker->sentence(2);
        $this->id = $this->faker->sha1;
        $this->value = $this->faker->word;
        $this->languageCode = $this->faker->languageCode;
    }

    public function testResponseJSONModel()
    {
        $this->assertJsonStringEqualsJsonString(
            $this->getSuccessResponse('json'),
            $this->getResponseModel('json')
        );
    }

    public function testResponseXMLModel()
    {
        $this->assertXmlStringEqualsXmlString(
            $this->getSuccessResponse('xml'),
            $this->getResponseModel('xml')
        );
    }

    public function testGetterSuccess()
    {
        /** @var  RestResponse $responseModel */
        $responseModel = $this->serializer->deserialize(
            $this->getSuccessResponse('json'),
            RestResponse::class,
            'json'
        );

        $this->assertEquals(200, $responseModel->getCode());
        $this->assertEquals('OK', $responseModel->getStatus());
        $this->assertEquals($this->scriptTimeSec, $responseModel->getScriptTimeSec());
        $this->assertEquals($this->trackId, $responseModel->getTrackId());
        $this->assertEquals(new \DateTime($this->date), $responseModel->getDate());

        foreach ($responseModel->getObjectValueType() as $objectValueType) {
            $this->assertEquals(200, $objectValueType->getCode());
            $this->assertEquals('OK', $objectValueType->getStatus());
            $this->assertEquals($this->id, $objectValueType->getId());
            $this->assertEquals($this->value, $objectValueType->getValue());
            $this->assertEquals($this->languageCode, $objectValueType->getLanguageCode());
            $this->assertEquals(new \DateTime($this->date), $objectValueType->getCreated());
            $this->assertEquals(new \DateTime($this->date), $objectValueType->getUpdated());
            break;
        }
    }

    public function testSetterError()
    {
        $responseErrorModel = new RestResponse();
        $responseErrorModel
            ->setCode(400)
            ->setScriptTimeSec($this->scriptTimeSec)
            ->setDate(new \DateTime($this->date))
            ->setTrackId($this->trackId);

        $objectValueType = new ObjectValueType();
        $objectValueType->setCode(400);

        $error = new Error();
        $error->setCode(400);
        $error->setMessage($this->message);
        $error->setException('external');

        $objectValueType->setError($error);
        $responseErrorModel->addObjectValueType($objectValueType);

        $this->assertJsonStringEqualsJsonString(
            $this->serializer->serialize($responseErrorModel, "json"),
            $this->getErrorResponse()
        );
    }

    public function testGetterError()
    {
        /** @var  RestResponse $responseModel */
        $responseModel = $this->serializer->deserialize(
            $this->getErrorResponse('json'),
            RestResponse::class,
            'json'
        );

        $this->assertEquals(400, $responseModel->getCode());
        $this->assertEquals('Bad Request', $responseModel->getStatus());
        $this->assertEquals($this->scriptTimeSec, $responseModel->getScriptTimeSec());
        $this->assertEquals($this->trackId, $responseModel->getTrackId());
        $this->assertEquals(new \DateTime($this->date), $responseModel->getDate());

        foreach ($responseModel->getObjectValueType() as $objectValueType) {
            $this->assertEquals(400, $objectValueType->getCode());
            $this->assertEquals('Bad Request', $objectValueType->getStatus());
            foreach ($objectValueType->getError() as $error) {
                $this->assertEquals(400, $error->getCode());
                $this->assertEquals($this->message, $error->getMessage());
                $this->assertEquals('external', $error->getException());
            }
            break;
        }
    }

    /**
     * @param string $type
     * @return string
     */
    private function getResponseModel($type = 'json')
    {
        $response = new RestResponse();
        $response
            ->setCode(200)
            ->setStatus('OK')
            ->setTrackId($this->trackId)
            ->setDate(new \DateTime($this->date))
            ->setScriptTimeSec($this->scriptTimeSec);

        $response->addObjectValueType($this->getObjectValueType());
        $responseModel = $this->serializer->serialize($response, $type);

        return $responseModel;
    }

    /**
     * @return ObjectValueType
     */
    private function getObjectValueType()
    {
        $objectValueType = new ObjectValueType();
        $objectValueType
            ->setCode(200)
            ->setStatus('OK');
        $objectValueType
            ->setId($this->id)
            ->setValue($this->value)
            ->setLanguageCode($this->languageCode)
            ->setCreated(new \DateTime($this->date))
            ->setUpdated(new \DateTime($this->date));

        return $objectValueType;
    }

    /**
     * @param string $type
     * @return string
     */
    private function getSuccessResponse($type = 'json')
    {
        if ($type === 'xml') {
            return '<?xml version="1.0" encoding="UTF-8"?>
                <objectValueUpdate>
                  <code>200</code>
                  <status><![CDATA[OK]]></status>
                  <trackId><![CDATA[' . $this->trackId . ']]></trackId>
                  <date><![CDATA[' . $this->date . ']]></date>
                  <scriptTimeSec>' . $this->scriptTimeSec . '</scriptTimeSec>
                  <objectValue>
                    <objectValueType>
                        <code>200</code>
                        <status><![CDATA[OK]]></status>
                        <id><![CDATA[' . $this->id . ']]></id>
                        <value><![CDATA[' . $this->value . ']]></value>
                        <languageCode><![CDATA[' . $this->languageCode . ']]></languageCode>
                        <created><![CDATA[' . $this->date . ']]></created>
                        <updated><![CDATA[' . $this->date . ']]></updated>
                    </objectValueType>
                  </objectValue>
                </objectValueUpdate>';
        } else {
            return '{
              "code": 200,
              "status": "OK",
              "trackId": "' . $this->trackId . '",
              "date": "' . $this->date . '",
              "scriptTimeSec": ' . $this->scriptTimeSec . ',
              "objectValue": [
                {
                  "code": 200,
                  "status": "OK",
                  "id": "' . $this->id . '",
                  "value": "' . $this->value . '",
                  "languageCode": "' . $this->languageCode . '",
                  "created": "' . $this->date . '",
                  "updated": "' . $this->date . '"
                }
              ]
            }';
        }
    }

    /**
     * @param string $type
     * @return string
     */
    private function getErrorResponse($type = 'json')
    {
        if ($type === 'xml') {
            return '<?xml version="1.0" encoding="UTF-8"?>
                      <objectValueUpdate>
                          <code>400</code>
                          <status><![CDATA[Bad Request]]></status>
                          <trackId><![CDATA[' . $this->trackId . ']]></trackId>
                          <date><![CDATA[' . $this->date . ']]></date>
                          <scriptTimeSec>' . $this->scriptTimeSec . '</scriptTimeSec>
                          <objectValue>
                              <objectValueType>
                                  <code>400</code>
                                  <status><![CDATA[Bad Request]]></status>
                                  <errors>
                                      <error>
                                          <code>400</code>
                                          <message><![CDATA[' . $this->message . ']]></message>
                                          <exception><![CDATA[external]]></exception>
                                      </error>
                                  </errors>
                              </objectValueType>
                          </objectValue>
                      </objectValueUpdate>';
        } else {
            return '{
                      "code": 400,
                      "status": "Bad Request",
                      "trackId": "' . $this->trackId . '",
                      "date": "' . $this->date . '",
                      "scriptTimeSec": ' . $this->scriptTimeSec . ',
                      "objectValue": [
                          {
                              "code": 400,
                              "status": "Bad Request",
                              "errors": [
                                  {
                                  "code": 400,
                                  "message": "' . $this->message . '",
                                  "exception": "external"
                                  }
                              ]
                          }
                      ]
                  }';
        }
    }
}
