<?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\User\Add;

use Sso\RestBundle\Api;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\User\Add\Error\Error;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\User\Add\Success\Add as SuccessAdd;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\User\Add\Success\Response as SuccessXmlResponse;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\User\Add\Success\User as SuccessUser;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\User\Add\Error\Response as ErrorXmlResponse;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\User\Add\Success\UserType as SuccessUserType;
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 $shortMessage;

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

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

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

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

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

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

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

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

    /**
     * @var boolean
     */
    private $deleted;

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

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

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

    /**
     * @var boolean
     */
    private $mfaEnabled;

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

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

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

    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->controller = $this->faker->word;
        $this->action = $this->faker->word;
        $this->date = '2099-01-01T00:00:00+00:00';
        $this->errorCount = $this->faker->randomNumber();
        $this->guid = $this->faker->md5;
        $this->email = $this->faker->email;
        $this->username = $this->faker->userName;
        $this->firstName = $this->faker->firstName;
        $this->lastName = $this->faker->lastName;
        $this->password = 'd5zJwgnzU2uTtv97';
        $this->active = $this->faker->boolean ? 1 : 0;
        $this->deleted = $this->faker->boolean ? 1 : 0;
        $this->createdAt = '2099-01-01T00:00:00+00:00';
        $this->updatedAt = '2099-01-01T00:00:00+00:00';
        $this->authId = $this->faker->randomNumber();
        $this->shortMessage = $this->faker->sentence(2);
        $this->message = $this->faker->sentence(4);
        $this->mfaEnabled = $this->faker->boolean ? 1 : 0;
    }

    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);
        $response->setStatus('OK');
        $response->setTrackId($this->trackId);
        $response->setDate(new \DateTime($this->date));
        $response->setScriptTimeSec($this->scriptTimeSec);

        $user = new SuccessUser();
        $add = new SuccessAdd();
        $userType = new SuccessUserType();

        $userType
            ->setGuid($this->guid)
            ->setUsername($this->username)
            ->setEmail($this->email)
            ->setFirstName($this->firstName)
            ->setLastName($this->lastName)
            ->setActive($this->active)
            ->setAuthId($this->authId)
            ->setLdapSearchAttributes('')
            ->setLdapSearchValue('');
        $userType
            ->setDeleted($this->deleted)
            ->setCreatedAt(new \DateTime($this->createdAt))
            ->setUpdatedAt(new \DateTime($this->updatedAt))
            ->setMfaEnabled($this->mfaEnabled);

        $add
            ->setStatus('Success')
            ->setUserType($userType);

        $user->setAdd($add);
        $response->setUser($user);
        $responseModel = $this->serializer->serialize($response, 'xml');

        return $responseModel;
    }

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

        $errors = new ArrayCollection();
        $error = new Error();

        $error
            ->setCode(400)
            ->setStatus('Bad Request')
            ->setErrorCode('fw003')
            ->setErrorRef('hd007')
            ->setShortMessage($this->shortMessage)
            ->setLongMessage($this->message)
            ->setType($this->shortMessage);

        $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>
                <User>
                    <Add>
                        <Status><![CDATA[Success]]></Status>
                        <UserType>
                            <Guid><![CDATA[' . $this->guid . ']]></Guid>
                            <Username><![CDATA[' . $this->username . ']]></Username>
                            <Email><![CDATA[' . $this->email . ']]></Email>
                            <Firstname><![CDATA[' . $this->firstName . ']]></Firstname>
                            <Lastname><![CDATA[' . $this->lastName . ']]></Lastname>
                            <Active>' . $this->active . '</Active>
                            <Deleted>' . $this->deleted . '</Deleted>
                            <CreatedAt><![CDATA[' . $this->createdAt . ']]></CreatedAt>
                            <UpdatedAt><![CDATA[' . $this->updatedAt . ']]></UpdatedAt>
                            <AuthId><![CDATA[' . $this->authId . ']]></AuthId>
                            <LdapSearchAttributes></LdapSearchAttributes>
                            <LdapSearchValue></LdapSearchValue>
                            <MfaEnabled>' . $this->mfaEnabled . '</MfaEnabled>
                        </UserType>
                    </Add>
                </User>
            </SsoResponse>';
    }

    /**
     * @return string
     */
    private function getErrorResponse()
    {
        return '<?xml version="1.0" encoding="utf-8"?>
            <SsoResponse>
                <Code>400</Code>
                <Status><![CDATA[Bad Request]]></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>400</Code>
                        <Status><![CDATA[Bad Request]]></Status>
                        <ErrorCode><![CDATA[fw003]]></ErrorCode>
                        <ErrorReference><![CDATA[hd007]]></ErrorReference>
                        <ShortMessage><![CDATA[' . $this->shortMessage . ']]></ShortMessage>
                        <LongMessage><![CDATA[' . $this->message . ']]></LongMessage>  
                        <Type><![CDATA[' . $this->shortMessage . ']]></Type>
                    </Error>
                </Errors>
            </SsoResponse>';
    }

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

        $add = $responseModel->getUser()->getAdd();
        $userType = $add->getUserType();

        $this->assertEquals(200, $responseModel->getCode());
        $this->assertEquals($this->scriptTimeSec, $responseModel->getScriptTimeSec());
        $this->assertEquals('OK', $responseModel->getStatus());
        $this->assertEquals($this->trackId, $responseModel->getTrackId());
        $this->assertEquals(new \DateTime($this->date), $responseModel->getDate());
        $this->assertEquals('Success', $add->getStatus());
        $this->assertEquals($this->guid, $userType->getGuid());
        $this->assertEquals($this->deleted, $userType->getDeleted());
        $this->assertEquals(new \DateTime($this->createdAt), $userType->getCreatedAt());
        $this->assertEquals(new \DateTime($this->updatedAt), $userType->getUpdatedAt());
        $this->assertEquals($this->mfaEnabled, $userType->getMfaEnabled());
    }

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

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

        $this->assertEquals(400, $responseModel->getCode());
        $this->assertEquals('Bad Request', $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(400, $error->getCode());
        $this->assertEquals('Bad Request', $error->getStatus());
        $this->assertEquals('fw003', $error->getErrorCode());
        $this->assertEquals('hd007', $error->getErrorRef());
        $this->assertEquals($this->shortMessage, $error->getShortMessage());
        $this->assertEquals($this->message, $error->getLongMessage());
        $this->assertEquals($this->shortMessage, $error->getType());
    }
}
