<?php

/**
 * Class ResponseTest
 *
 * 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  2017 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

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

use Sso\RestBundle\Api;
use Sso\RestBundle\ModelRest\Response\ObjectWs\Version1\Object\Update\Response as RestResponse;
use Sso\RestBundle\ModelRest\Response\ObjectWs\Version1\Object\Update\Object;
use GuzzleHttp\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Sso\RestBundle\ModelRest\Common\Response\UserWs\ErrorCollector;
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
     */
    private $client;

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @var int
     */
    private $active;

    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->name = $this->faker->name;
        $this->description = $this->faker->sentence();
        $this->referenceId = $this->faker->md5;
        $this->guid = $this->faker->uuid;
        $this->typeId = $this->faker->uuid;
        $this->active = $this->faker->boolean ? 1 : 0;
    }

    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->getObjects() as $object) {
            $this->assertEquals(200, $object->getCode());
            $this->assertEquals('OK', $object->getStatus());
            $this->assertEquals($this->guid, $object->getGuid());
            $this->assertEquals($this->referenceId, $object->getReferenceId());
            $this->assertEquals($this->typeId, $object->getTypeId());
            $this->assertEquals($this->guid, $object->getParentGuid());
            $this->assertEquals($this->name, $object->getName());
            $this->assertEquals(new \DateTime($this->date), $object->getCreated());
            $this->assertEquals(new \DateTime($this->date), $object->getUpdated());
            $this->assertEquals($this->active, $object->getActive());
            break;
        }
    }

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

        $object = new Object();
        $object->setCode(400);

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

        $object->setError($error);
        $responseErrorModel->setObject($object);

        $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->getObjects() as $object) {
            $this->assertEquals(400, $object->getCode());
            $this->assertEquals('Bad Request', $object->getStatus());
            foreach ($object->getErrors() 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->setObject($this->getObject());
        return $this->serializer->serialize($response, $type);
    }

    /**
     * @return Object
     */
    private function getObject()
    {
        $object = new Object();
        $object
            ->setCode(200)
            ->setStatus('OK');
        $object
            ->setGuid($this->guid)
            ->setReferenceId($this->referenceId)
            ->setTypeId($this->typeId)
            ->setParentGuid($this->guid)
            ->setName($this->name)
            ->setCreated(new \DateTime($this->date))
            ->setUpdated(new \DateTime($this->date))
            ->setActive($this->active);

        return $object;
    }

    /**
     * @param string $type
     * @return string
     */
    private function getSuccessResponse($type = 'json')
    {
        if ($type === 'xml') {
            return '<?xml version="1.0" encoding="UTF-8"?>
                <objectUpdate>
                  <code>200</code>
                  <status><![CDATA[OK]]></status>
                  <trackId><![CDATA[' . $this->trackId . ']]></trackId>
                  <date><![CDATA[' . $this->date . ']]></date>
                  <scriptTimeSec>' . $this->scriptTimeSec . '</scriptTimeSec>
                  <objects>
                    <object>
                        <code>200</code>
                        <status><![CDATA[OK]]></status>
                        <guid><![CDATA[' . $this->guid . ']]></guid>
                        <referenceId><![CDATA[' . $this->referenceId . ']]></referenceId>
                        <typeId><![CDATA[' . $this->typeId . ']]></typeId>
                        <parentGuid><![CDATA[' . $this->guid . ']]></parentGuid>
                        <name><![CDATA[' . $this->name . ']]></name>
                        <created><![CDATA[' . $this->date . ']]></created>
                        <updated><![CDATA[' . $this->date . ']]></updated>
                        <active>' . $this->active . '</active>
                    </object>
                  </objects>
                </objectUpdate>';
        } else {
            return '{
              "code": 200,
              "status": "OK",
              "trackId": "' . $this->trackId . '",
              "date": "' . $this->date . '",
              "scriptTimeSec": ' . $this->scriptTimeSec . ',
              "objects": [
                {
                  "code": 200,
                  "status": "OK",
                  "guid": "' . $this->guid . '",
                  "referenceId": "' . $this->referenceId . '",
                  "typeId": "' . $this->typeId . '",
                  "parentGuid": "' . $this->guid . '",
                  "name": "' . $this->name . '",
                  "created": "' . $this->date . '",
                  "updated": "' . $this->date . '",
                  "active": ' . $this->active . '
                }
              ]
            }';
        }
    }

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