<?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\ModelXml\Response\UserWs\Version2\UserSearch\FindByApplicationRole;

use Sso\RestBundle\Api;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserSearch\FindByApplicationRole\Success\UserType;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserSearch\FindByApplicationRole\Error\Error;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserSearch\FindByApplicationRole\Success\UserSearch;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserSearch\FindByApplicationRole\Success\FindByApplicationRole as SuccessFindByApplicationRole;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserSearch\FindByApplicationRole\Success\Response as SuccessXmlResponse;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserSearch\FindByApplicationRole\Error\Response as ErrorXmlResponse;
use Doctrine\Common\Collections\ArrayCollection;
use GuzzleHttp\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Faker\Factory as FakerFactory;
use Faker\Generator as FakerGenerator;

/**
 * Class 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 float
     */
    private $scriptTimeSec;

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @var integer
     */
    private $errorCount;

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

    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->scriptTimeSec = $this->faker->randomFloat(2);
        $this->trackId = $this->faker->md5;
        $this->date = '2099-01-01T00:00:00+00:00';
        $this->message = $this->faker->sentence(2);
        $this->name = $this->faker->word;
        $this->description = $this->faker->sentence();
        $this->active = $this->faker->boolean ? 1 : 0;
        $this->guid = $this->faker->md5;
        $this->username = $this->faker->userName;
        $this->email = $this->faker->email;
        $this->controller = $this->faker->word;
        $this->action = $this->faker->word;
        $this->errorCount = $this->faker->randomNumber();
        $this->type = $this->faker->word;
    }

    public function testSuccessResponseModel()
    {
        $this->assertXmlStringEqualsXmlString($this->getSuccessResponse(), $this->getSuccessResponseModel());
    }

    public function testErrorResponseModel()
    {
        $this->assertXmlStringEqualsXmlString($this->getErrorResponse(), $this->getErrorResponseModel());
    }

    private function getSuccessResponseModel()
    {
        $response = new SuccessXmlResponse();
        $response
            ->setCode(200)
            ->setStatus('OK')
            ->setTrackId($this->trackId)
            ->setDate(new \DateTime($this->date))
            ->setScriptTimeSec($this->scriptTimeSec);

        $findByApplicationAttribute = new SuccessFindByApplicationRole();
        $userSearch = new UserSearch();
        $userType = new UserType();

        $userType
            ->setGuid($this->guid)
            ->setUsername($this->username)
            ->setEmail($this->email)
            ->setActive($this->active);

        $findByApplicationAttribute->setUserType($userType);
        $findByApplicationAttribute
            ->setStatus('OK')
            ->setUserType($userType);

        $userSearch->setFindByApplicationRole($findByApplicationAttribute);
        $response->setUserSearch($userSearch);

        $responseModel = $this->serializer->serialize($response, 'xml');

        return $responseModel;
    }

    private function getErrorResponseModel()
    {
        $response = new ErrorXmlResponse();
        $response
            ->setCode(404)
            ->setStatus('Not Found')
            ->setTrackId($this->trackId)
            ->setController($this->controller)
            ->setAction($this->action)
            ->setDate(new \DateTime($this->date))
            ->setScriptTimeSec($this->scriptTimeSec)
            ->setErrorCount($this->errorCount);

        $error = new Error();
        $error
            ->setCode(404)
            ->setStatus('Not Found')
            ->setErrorCode('fw003')
            ->setErrorRef('hd007')
            ->setShortMessage($this->message)
            ->setLongMessage($this->message)
            ->setType($this->type);

        $errors = new ArrayCollection();
        $errors->add($error);
        $response->setErrors($errors);

        $responseModel = $this->serializer->serialize($response, 'xml');

        return $responseModel;
    }

    /**
     * @return string
     */
    private function getSuccessResponse()
    {
        return '<?xml version="1.0" encoding="utf-8"?>
            <SsoResponse>
              <Code>200</Code>
              <Status><![CDATA[OK]]></Status>
              <Trackid><![CDATA[' . $this->trackId . ']]></Trackid>
              <Date><![CDATA[' . $this->date . ']]></Date>
              <ScriptTimeSec>' . $this->scriptTimeSec . '</ScriptTimeSec>
              <UserSearch>
                <FindByApplicationRole>
                  <Status><![CDATA[OK]]></Status>
                  <UserType>
                      <Guid><![CDATA[' . $this->guid . ']]></Guid>
                      <Email><![CDATA[' . $this->email . ']]></Email>
                      <Username><![CDATA[' . $this->username . ']]></Username>
                      <Active>' . $this->active . '</Active>
                  </UserType>
                 </FindByApplicationRole>
              </UserSearch>
            </SsoResponse>';
    }

    /**
     * @return string
     */
    private function getErrorResponse()
    {
        return '<?xml version="1.0" encoding="utf-8"?>
            <SsoResponse>
                <Code>404</Code>
                <Status><![CDATA[Not Found]]></Status>
                <TrackId><![CDATA[' . $this->trackId . ']]></TrackId>
                <Controller><![CDATA[' . $this->controller . ']]></Controller>
                <Action><![CDATA[' . $this->action . ']]></Action>
                <Date><![CDATA[' . $this->date . ']]></Date>
                <ScriptTimeSec>' . $this->scriptTimeSec . '</ScriptTimeSec>
                <ErrorCount>' . $this->errorCount . '</ErrorCount>
                <Errors>
                    <Error>
                        <Code>404</Code>
                        <Status><![CDATA[Not Found]]></Status>
                        <ErrorCode><![CDATA[fw003]]></ErrorCode>
                        <ErrorReference><![CDATA[hd007]]></ErrorReference>
                        <ShortMessage><![CDATA[' . $this->message . ']]></ShortMessage>
                        <LongMessage><![CDATA[' . $this->message . ']]></LongMessage>
                        <Type><![CDATA[' . $this->type . ']]></Type>
                    </Error>
                </Errors>
            </SsoResponse>';
    }

    public function testSuccessGetters()
    {
        /** @var SuccessXmlResponse $responseModel */
        $responseModel = $this->serializer->deserialize(
            $this->getSuccessResponseModel(),
            SuccessXmlResponse::class,
            'xml'
        );

        $userType = $responseModel->getUserSearch()->getFindByApplicationRole()->getUserType()->get(0);

        $this->assertEquals(200, $responseModel->getCode());
        $this->assertEquals('OK', $responseModel->getStatus());
        $this->assertEquals($this->trackId, $responseModel->getTrackId());
        $this->assertEquals(new \DateTime($this->date), $responseModel->getDate());
        $this->assertEquals($this->scriptTimeSec, $responseModel->getScriptTimeSec());
        $this->assertEquals('OK', $responseModel->getUserSearch()->getFindByApplicationRole()->getStatus());
        $this->assertEquals($this->guid, $userType->getGuid());
        $this->assertEquals($this->username, $userType->getUsername());
        $this->assertEquals($this->email, $userType->getEmail());
        $this->assertEquals($this->active, $userType->getActive());
    }

    public function testErrorGetters()
    {
        /** @var ErrorXmlResponse $responseModel */
        $responseModel = $this->serializer->deserialize(
            $this->getErrorResponseModel(),
            ErrorXmlResponse::class,
            'xml'
        );

        $error = $responseModel->getErrors()->get(0);

        $this->assertEquals(404, $responseModel->getCode());
        $this->assertEquals('Not Found', $responseModel->getStatus());
        $this->assertEquals($this->trackId, $responseModel->getTrackId());
        $this->assertEquals($this->controller, $responseModel->getController());
        $this->assertEquals($this->action, $responseModel->getAction());
        $this->assertEquals(new \DateTime($this->date), $responseModel->getDate());
        $this->assertEquals($this->scriptTimeSec, $responseModel->getScriptTimeSec());
        $this->assertEquals($this->errorCount, $responseModel->getErrorCount());
        $this->assertEquals(404, $error->getCode());
        $this->assertEquals('Not Found', $error->getStatus());
        $this->assertEquals('fw003', $error->getErrorCode());
        $this->assertEquals('hd007', $error->getErrorRef());
        $this->assertEquals($this->message, $error->getShortMessage());
        $this->assertEquals($this->message, $error->getLongMessage());
        $this->assertEquals($this->type, $error->getType());
    }
}
