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

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

use Sso\RestBundle\Api\Manager as ApiManager;
use Sso\RestBundle\ModelRest\Common\Response\UserWs\ErrorCollector;
use Sso\RestBundle\ModelRest\Response\ObjectWs\Version1\AttributeGroup\Update;
use Faker\Factory as FakerFactory;
use Faker\Generator as FakerGenerator;
use JMS\Serializer\Serializer;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * Class ResponseTest
 * @package Sso\RestBundle\Tests\ModelRest\Response\ObjectWs\Version1\AttributeGroup\Update
 */
class ResponseTest extends WebTestCase
{
    /**
     * @var Serializer
     */
    private $serializer;

    /**
     * @var ApiManager
     */
    private $apiManager;

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

    /**
     * @var Update\Response
     */
    private $errorResponse;

    /**
     * @var Update\Response
     */
    private $successResponse;

    protected function setUp()
    {
        parent::setUp();
        static::bootKernel();
        $this->apiManager = new ApiManager(static::$kernel->getContainer());
        $this->serializer = $this->apiManager->serializer();
        $this->faker = FakerFactory::create();

        $this->setUpErrorResponse();
        $this->setUpSuccessResponse();
    }

    private function setUpErrorResponse()
    {
        $response = new Update\Response();
        $attributeGroup = new Update\AttributeGroup();
        $error = new ErrorCollector\Error();

        $attributeGroup
            ->addError($error)
            ->setId($this->faker->uuid)
            ->setName($this->faker->name)
            ->setCode($this->faker->numberBetween(100, 400))
            ->setStatus($this->faker->word);

        $response
            ->addAttributeGroup($attributeGroup)
            ->setCode($this->faker->numberBetween(100, 400))
            ->setStatus($this->faker->word)
            ->setTrackId($this->faker->word)
            ->setDate($this->faker->dateTime)
            ->setScriptTimeSec(round($this->faker->randomFloat(), 3));

        $error
            ->setCode($this->faker->numberBetween(100, 400))
            ->setMessage($this->faker->text)
            ->setException($this->faker->word);

        $this->errorResponse = $response;
    }

    private function setUpSuccessResponse()
    {
        $response = new Update\Response();
        $attributeGroup = new Update\AttributeGroup();

        $attributeGroup
            ->setId($this->faker->uuid)
            ->setName($this->faker->name)
            ->addTypeId($this->faker->uuid)
            ->setCode($this->faker->numberBetween(100, 400))
            ->setStatus($this->faker->word);

        $response
            ->addAttributeGroup($attributeGroup)
            ->setCode($this->faker->numberBetween(100, 400))
            ->setStatus($this->faker->word)
            ->setTrackId($this->faker->word)
            ->setDate($this->faker->dateTime)
            ->setScriptTimeSec(1.22);

        $this->successResponse = $response;
    }

    public function testGetAndAddAttributeGroup()
    {
        $response = new Update\Response();
        $attributeGroup = new Update\AttributeGroup();

        $response->addAttributeGroup($attributeGroup);

        static::assertNotEmpty($response->getAttributeGroups());
        static::assertEquals($response->getAttributeGroups()->get(0), $attributeGroup);
    }

    public function testJSONSerializeError()
    {
        static::assertJsonStringEqualsJsonString(
            $this->serializer->serialize($this->errorResponse, 'json'),
            $this->getSerializedErrorResponseContent('json')
        );
    }

    public function testXMLSerializeError()
    {
        static::assertXmlStringEqualsXmlString(
            $this->serializer->serialize($this->errorResponse, 'xml'),
            $this->getSerializedErrorResponseContent('xml')
        );
    }

    public function testJSONSerializeSuccess()
    {
        static::assertJsonStringEqualsJsonString(
            $this->serializer->serialize($this->successResponse, 'json'),
            $this->getSerializedSuccessResponseContent('json')
        );
    }

    public function testXMLSerializeSuccess()
    {
        static::assertXmlStringEqualsXmlString(
            $this->serializer->serialize($this->successResponse, 'xml'),
            $this->getSerializedSuccessResponseContent('xml')
        );
    }

    /**
     * @param string $type (xml | json)
     *
     * @return string
     */
    private function getSerializedErrorResponseContent($type = 'xml')
    {
        switch ($type) {
            case 'json':
                return <<< JSON
{
    "code": {$this->errorResponse->getCode()},
    "status": "{$this->errorResponse->getStatus()}",
    "trackId": "{$this->errorResponse->getTrackId()}",
    "date": "{$this->errorResponse->getDate()->format(\DateTime::ATOM)}",
    "scriptTimeSec": {$this->errorResponse->getScriptTimeSec()},
    "attributeGroups": [
        {
            "code": {$this->errorResponse->getAttributeGroups()->get(0)->getCode()},
            "status": "{$this->errorResponse->getAttributeGroups()->get(0)->getStatus()}",
            "id": "{$this->errorResponse->getAttributeGroups()->get(0)->getId()}",
            "name": "{$this->errorResponse->getAttributeGroups()->get(0)->getName()}",
            "errors": [
                {
                    "code": {$this->errorResponse->getAttributeGroups()->get(0)->getErrors()->get(0)->getCode()},
                    "message": "{$this->errorResponse->getAttributeGroups()->get(0)->getErrors()->get(0)->getMessage()}",
                    "exception": "{$this->errorResponse->getAttributeGroups()->get(0)->getErrors()->get(0)->getException()}"
                }
            ]
        }
    ]
}
JSON;
            case 'xml':
                return <<< XML
<?xml version="1.0" encoding="UTF-8"?>
<attributeGroupUpdate>
    <code>{$this->errorResponse->getCode()}</code>
    <status>
        <![CDATA[{$this->errorResponse->getStatus()}]]>
    </status>
    <trackId>
        <![CDATA[{$this->errorResponse->getTrackId()}]]>
    </trackId>
    <date>
        <![CDATA[{$this->errorResponse->getDate()->format(\DateTime::ATOM)}]]>
    </date>
    <scriptTimeSec>{$this->errorResponse->getScriptTimeSec()}</scriptTimeSec>
    <attributeGroups>
        <attributeGroup>
            <code>{$this->errorResponse->getAttributeGroups()->get(0)->getCode()}</code>
            <status>
                <![CDATA[{$this->errorResponse->getAttributeGroups()->get(0)->getStatus()}]]>
            </status>
            <id>
                <![CDATA[{$this->errorResponse->getAttributeGroups()->get(0)->getId()}]]>
            </id>
            <name>
                <![CDATA[{$this->errorResponse->getAttributeGroups()->get(0)->getName()}]]>
            </name>
            <errors>
                <error>
                    <code>{$this->errorResponse->getAttributeGroups()->get(0)->getErrors()->get(0)->getCode()}</code>
                    <message>
                        <![CDATA[{$this->errorResponse->getAttributeGroups()->get(0)->getErrors()->get(0)->getMessage()}]]>
                    </message>
                    <exception>
                        <![CDATA[{$this->errorResponse->getAttributeGroups()->get(0)->getErrors()->get(0)->getException()}]]>
                    </exception>
                </error>
            </errors>
        </attributeGroup>
    </attributeGroups>
</attributeGroupUpdate>
XML;
            default:
                throw new \PHPUnit_Framework_Exception('Invalid request type (hint: not json/xml)');
        }
    }

    /**
     * @param string $type (xml | json)
     *
     * @return string
     */
    private function getSerializedSuccessResponseContent($type = 'xml')
    {
        switch ($type) {
            case 'json':
                return <<< JSON
{
    "code": {$this->successResponse->getCode()},
    "status": "{$this->successResponse->getStatus()}",
    "trackId": "{$this->successResponse->getTrackId()}",
    "date": "{$this->successResponse->getDate()->format(\DateTime::ATOM)}",
    "scriptTimeSec": {$this->successResponse->getScriptTimeSec()},
    "attributeGroups": [
        {
            "code": {$this->successResponse->getAttributeGroups()->get(0)->getCode()},
            "status": "{$this->successResponse->getAttributeGroups()->get(0)->getStatus()}",
            "id": "{$this->successResponse->getAttributeGroups()->get(0)->getId()}",
            "name": "{$this->successResponse->getAttributeGroups()->get(0)->getName()}",
            "ids": [
                "{$this->successResponse->getAttributeGroups()->get(0)->getTypeIds()->get(0)}"
            ]
        }
    ]
}
JSON;
            case 'xml':
                return <<< XML
<?xml version="1.0" encoding="UTF-8"?>
<attributeGroupUpdate>
    <code>{$this->successResponse->getCode()}</code>
    <status>
        <![CDATA[{$this->successResponse->getStatus()}]]>
    </status>
    <trackId>
        <![CDATA[{$this->successResponse->getTrackId()}]]>
    </trackId>
    <date>
        <![CDATA[{$this->successResponse->getDate()->format(\DateTime::ATOM)}]]>
    </date>
    <scriptTimeSec>{$this->successResponse->getScriptTimeSec()}</scriptTimeSec>
    <attributeGroups>
        <attributeGroup>
            <code>{$this->successResponse->getAttributeGroups()->get(0)->getCode()}</code>
            <status>
                <![CDATA[{$this->successResponse->getAttributeGroups()->get(0)->getStatus()}]]>
            </status>
            <id>
                <![CDATA[{$this->successResponse->getAttributeGroups()->get(0)->getId()}]]>
            </id>
            <name>
                <![CDATA[{$this->successResponse->getAttributeGroups()->get(0)->getName()}]]>
            </name>
            <ids>
                <id>
                    <![CDATA[{$this->successResponse->getAttributeGroups()->get(0)->getTypeIds()->get(0)}]]>
                </id>
            </ids>
        </attributeGroup>
    </attributeGroups>
</attributeGroupUpdate>
XML;
            default:
                throw new \PHPUnit_Framework_Exception('Invalid request type (hint: not json/xml)');
        }
    }
}

