<?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\ModelXml\Response\UserWs\Version2\UserApplication\Show;

use Sso\RestBundle\Api;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserApplication\Show\Error\Error;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserApplication\Show\Success\ApplicationType;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserApplication\Show\Success\UserType;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserApplication\Show\Success\Show as SuccessShow;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserApplication\Show\Success\Response as SuccessXmlResponse;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserApplication\Show\Success\UserApplication as SuccessUserApplication;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserApplication\Show\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 string
     */
    private $attrName;

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @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->attrName = $this->faker->word;
        $this->attrType = $this->faker->word;
        $this->attrValue = $this->faker->word;
        $this->appName = $this->faker->word;
        $this->active = $this->faker->boolean ? 1 : 0;
        $this->guid = $this->faker->md5;
        $this->username = $this->faker->userName;
        $this->email = $this->faker->email;
        $this->firstName = $this->faker->firstName;
        $this->lastName = $this->faker->lastName;
        $this->authId = $this->faker->md5;
        $this->deleted = $this->faker->boolean ? 1 : 0;
        $this->mfaEnabled = $this->faker->boolean ? 1 : 0;
        $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);
        $response->setStatus('OK');
        $response->setTrackId($this->trackId);
        $response->setDate(new \DateTime($this->date));
        $response->setScriptTimeSec($this->scriptTimeSec);

        $userApplication = new SuccessUserApplication();
        $userType = new UserType();
        $applicationType = new ApplicationType();
        $show = new SuccessShow();

        $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->date))
            ->setUpdatedAt(new \DateTime($this->date))
            ->setMfaEnabled($this->mfaEnabled);

        $applicationType
            ->setName($this->appName)
            ->setActive($this->active);

        $show
            ->setStatus('OK')
            ->setUserType($userType)
            ->setApplicationType($applicationType);

        $userApplication->setShow($show);
        $response->setUserApplication($userApplication);

        $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>
              <UserApplication>
                <Show>
                  <Status><![CDATA[OK]]></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->date . ']]></CreatedAt>
                      <UpdatedAt><![CDATA[' . $this->date . ']]></UpdatedAt>
                      <AuthId><![CDATA[' . $this->authId . ']]></AuthId>
                      <LdapSearchAttributes><![CDATA[]]></LdapSearchAttributes>
                      <LdapSearchValue><![CDATA[]]></LdapSearchValue>
                      <MfaEnabled>' . $this->mfaEnabled . '</MfaEnabled>
                  </UserType>
                  <ApplicationType>
                      <Name><![CDATA[' . $this->appName . ']]></Name>
                      <Active>' . $this->active . '</Active>
                  </ApplicationType>
                 </Show>
              </UserApplication>
            </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'
        );

        $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->getUserApplication()->getShow()->getStatus());
        $this->assertEquals($this->guid, $responseModel->getUserApplication()->getShow()->getUserType()->getGuid());
        $this->assertEquals($this->username,
            $responseModel->getUserApplication()->getShow()->getUserType()->getUsername());
        $this->assertEquals($this->email, $responseModel->getUserApplication()->getShow()->getUserType()->getEmail());
        $this->assertEquals($this->firstName,
            $responseModel->getUserApplication()->getShow()->getUserType()->getFirstName());
        $this->assertEquals($this->lastName,
            $responseModel->getUserApplication()->getShow()->getUserType()->getLastName());
        $this->assertEquals($this->active, $responseModel->getUserApplication()->getShow()->getUserType()->getActive());
        $this->assertEquals($this->deleted,
            $responseModel->getUserApplication()->getShow()->getUserType()->getDeleted());
        $this->assertEquals(new \DateTime($this->date),
            $responseModel->getUserApplication()->getShow()->getUserType()->getCreatedAt());
        $this->assertEquals(new \DateTime($this->date),
            $responseModel->getUserApplication()->getShow()->getUserType()->getUpdatedAt());
        $this->assertEquals($this->authId, $responseModel->getUserApplication()->getShow()->getUserType()->getAuthId());
        $this->assertEquals('',
            $responseModel->getUserApplication()->getShow()->getUserType()->getLdapSearchAttributes());
        $this->assertEquals('', $responseModel->getUserApplication()->getShow()->getUserType()->getLdapSearchValue());
        $this->assertEquals($this->mfaEnabled,
            $responseModel->getUserApplication()->getShow()->getUserType()->getMfaEnabled());

        foreach ($responseModel->getUserApplication()->getShow()->getApplicationType() as $applicationType) {
            $this->assertEquals($this->appName, $applicationType->getName());
            $this->assertEquals($this->active, $applicationType->getActive());

            break;
        }
    }

    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());
    }
}
