<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private 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\WebserviceBundle\Tests\Services\User\Show\Response\Version2;

use Sso\WebserviceBundle\Api\ApiManagerInterface;
use Sso\WebserviceBundle\ErrorHandler\ErrorHandlerInterface;
use Sso\WebserviceBundle\Services\User\Show\ResponseData\User as ResponseDataUser;
use Sso\WebserviceBundle\Services\User\Show\Response\Version2\ResponseBuilder;
use Sso\WebserviceBundle\Services\User\Show\Response\Version2\Factory;
use Sso\WebserviceBundle\Api\Exception\Type\Api as ApiException;
use JMS\Serializer\SerializerBuilder;
use Sso\WebserviceBundle\Entity\Webservice\Type\User as UserModel;
use Symfony\Component\Validator\Validator\ValidatorInterface;

/**
 * Class ResponseBuilderTest
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package Sso\WebserviceBundle\Tests\Services\User\Show\Response\Version2
 */
class ResponseBuilderTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @var ApiManagerInterface
     */
    private $apiManager;

    protected function setUp()
    {
        $this->apiManager = $this->createMock(ApiManagerInterface::class);
    }

    public function testSetResponseSuccess()
    {
        $user = new ResponseDataUser();
        $userData = $this->userDataProvider();
        $user = $user->setFromUserModel($userData);

        $responseBuilder = $this->factoryResponseBuilder();
        $responseBuilder->setResponse($user);

        self::assertAttributeEquals($user, 'responseData', $responseBuilder);
    }

    /**
     * @param array $userData
     */
    public function testBuildResponseSuccess()
    {
        // Overwrite track-id, because otherwise it will be in response xml
        ApiException::setTrackId('');

        $user = new ResponseDataUser();
        $userData = $this->userDataProvider();
        $user = $user->setFromUserModel($userData);

        $responseBuilder = $this->factoryResponseBuilder();
        $responseBuilder->setResponse($user);
        $responseXml = $responseBuilder->build('xml');

        $successXML = $this->generateSuccessXml($userData);

        $responseObject = simplexml_load_string($responseXml);
        $successObject = simplexml_load_string($successXML);


        $this->assertSame($responseObject->SsoResponse->Code, $successObject->SsoResponse->Code);
        $this->assertSame($responseObject->SsoResponse->Status, $successObject->SsoResponse->Status);
        $this->assertRegexp('/'.$user->getGuid().'/', $responseXml);
        $this->assertRegexp('/'.$user->getUsername().'/', $responseXml);
        $this->assertRegexp('/'.$user->getEmail().'/', $responseXml);
        $this->assertRegexp('/'.$user->getFirstname().'/', $responseXml);
        $this->assertRegexp('/'.$user->getLastname().'/', $responseXml);
        $this->assertRegexp('/'.$user->getLdapSearchAttributes().'/', $responseXml);
        $this->assertRegexp('/'.$user->getLdapSearchValue().'/', $responseXml);
    }

    /**
     * @return ResponseBuilder
     */
    private function factoryResponseBuilder()
    {
        $serializer = SerializerBuilder::create()->build();
        $factory = new Factory($this->apiManager);
        $errorHandler = $this->createMock(ErrorHandlerInterface::class);
        return new ResponseBuilder($serializer, $factory, $errorHandler);
    }

    /**
     * @return UserModel
     */
    public function userDataProvider()
    {
        $validator = $this->createMock(ValidatorInterface::class);
        $faker = \Faker\Factory::create();
        $user = new UserModel($validator);
        $user->setGuid($faker->uuid);
        $user->setUsername($faker->userName);
        $user->setEmail($faker->email);
        $user->setFirstname($faker->firstName);
        $user->setLastname($faker->lastName);
        $user->setActive(1);
        $user->setDeleted(0);
        $user->setAuthId($faker->sha256);
        $user->setLdapSearchAttributes($faker->sha256);
        $user->setLdapSearchValue($faker->sha256);
        $user->setMfaEnabled(true);

        return $user;
    }

    /**
     * @param array $user
     * @return string
     */
    private function generateSuccessXml(UserModel $user)
    {
        return '<?xml version="1.0"?>
                <SsoResponse>
                    <Code>200</Code>
                    <Status>OK</Status>
                    <Trackid></Trackid>
                    <Date>' . (new \DateTime())->format('Y-m-d H:i:s') . '</Date>
                    <User>
                        <Show>
                            <UserType>
                                <Guid><![CDATA['.$user->getGuid().']]></Guid>
                                <Username><![CDATA['.$user->getUsername().']]></Username>
                                <Email><![CDATA['.$user->getEmail().']]></Email>
                                <Firstname><![CDATA['.$user->getFirstname().']]></Firstname>
                                <Lastname><![CDATA['.$user->getLastname().']]></Lastname>
                                <Active>'.$user->getActive().'</Active>
                                <Deleted>0</Deleted>
                                <AuthId>'.$user->getAuthId().'</AuthId>
                                <LdapSearchAttributes><![CDATA['.$user->getLdapSearchAttributes().']]></LdapSearchAttributes>
                                <LdapSearchValue><![CDATA['.$user->getLdapSearchValue().']]></LdapSearchValue>
                                <MfaEnabled>'.$user->isMfaEnabled().'</MfaEnabled>
                            </UserType>
                        </Show>
                    </User>
                </SsoResponse>';
    }
}
