<?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\Request\UserWs\Version2\UserSearch\Advanced;

use Sso\RestBundle\ModelShared\Request\UserWs\Version2\UserSearch\Advanced\ApplicationType;
use Sso\RestBundle\ModelShared\Request\UserWs\Version2\UserSearch\Advanced\AttributeType;
use Sso\RestBundle\ModelShared\Request\UserWs\Version2\UserSearch\Advanced\Filter;
use Sso\RestBundle\ModelShared\Request\UserWs\Version2\UserSearch\Advanced\Filters;
use Sso\RestBundle\ModelShared\Request\UserWs\Version2\UserSearch\Advanced\UserType;
use Sso\RestBundle\ModelXml\Common\Request\Credentials\UserWs\Credentials;
use Sso\RestBundle\ModelXml\Request\UserWs\Version2\UserSearch\Advanced\Advanced;
use Sso\RestBundle\ModelXml\Request\UserWs\Version2\UserSearch\Advanced\Request;
use Sso\RestBundle\ModelXml\Request\UserWs\Version2\UserSearch\Advanced\UserSearch;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Sso\RestBundle\Api\Manager as ApiManager;
use JMS\Serializer\SerializerInterface;
use Faker\Factory as FakerFactory;
use Faker\Generator as FakerGenerator;

/**
 * Class RequestTest
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package Sso\RestBundle\Tests\ModelRest
 */
class RequestTest extends WebTestCase
{
    /**
     * @var SerializerInterface
     */
    private $serializer;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // Set same random data
        $this->serviceToken = $this->faker->sha256;
        $this->serviceName = $this->faker->word;
        $this->userIdentifier = $this->faker->md5;
        $this->username = $this->faker->userName;
        $this->langCode = $this->faker->languageCode;
        $this->date = '2099-01-01T00:00:00+00:00';
        $this->offset = $this->faker->numberBetween(0, 10);
        $this->limit = $this->faker->numberBetween(0, 1000);
        $this->fullResponse = $this->faker->boolean ? 1 : 0;
        $this->orderDir = $this->faker->randomElement(['ASC', 'DESC']);
        $this->operator = $this->faker->randomElement(['AND', 'OR', 'AND NOT']);
        $this->strategy = $this->faker->randomElement([
            'EQ',
            'NOT EQ',
            'GT',
            'GTE',
            'LT',
            'LTE',
            'LIKE',
            'NOT LIKE',
            'REGEX'
        ]);
        $this->guid = $this->faker->uuid;
        $this->username = $this->faker->userName;
        $this->email = $this->faker->email;
        $this->firstName = $this->faker->firstName;
        $this->lastName = $this->faker->lastName;
        $this->active = $this->faker->boolean ? 1 : 0;
        $this->deleted = $this->faker->boolean ? 1 : 0;
        $this->authId = $this->faker->md5;
        $this->mfaEnabled = $this->faker->boolean ? 1 : 0;
        $this->name = $this->faker->word;
        $this->attrValue = $this->faker->sentence(2);
    }

    public function testSerialize()
    {
        $this->assertXmlStringEqualsXmlString($this->getRequestBody(), $this->setRequestBody());
    }

    /**
     * @return string
     */
    private function setRequestBody()
    {
        $request = new Request();
        $credentials = new Credentials();
        $userSearch = new UserSearch();
        $advanced = new Advanced();
        $filters = new Filters();
        $filters2 = new Filters();
        $filter = new Filter();
        $filter2 = new Filter();
        $filter3 = new Filter();
        $userType = new UserType();
        $applicationType = new ApplicationType();
        $attributeType = new AttributeType();

        $credentials->setCredentialsData(
            $this->serviceToken,
            $this->serviceName,
            $this->userIdentifier,
            $this->username,
            $this->langCode
        );

        // userType filter
        $userType
            ->setGuid($this->guid)
            ->setUsername($this->username)
            ->setEmail($this->email)
            ->setFirstname($this->firstName)
            ->setLastname($this->lastName)
            ->setActive($this->active)
            ->setDeleted($this->deleted)
            ->setCreatedAt(new \DateTime($this->date))
            ->setUpdatedAt(new \DateTime($this->date))
            ->setMfaEnabled($this->mfaEnabled);

        $filter
            ->setStrategy($this->strategy)
            ->setOperator($this->operator)
            ->setUserType($userType);

        // application / attribute filter
        $attributeType
            ->setName($this->name)
            ->setValue($this->attrValue)
            ->setActive($this->active);

        $applicationType
            ->setName($this->name)
            ->setActive($this->active)
            ->setAttributeType($attributeType);

        $filter3
            ->setStrategy($this->strategy)
            ->setOperator($this->operator)
            ->setApplicationType($applicationType);

        $filters2->addFilter($filter3);

        // filter of filters
        $filter2
            ->setStrategy($this->strategy)
            ->setOperator($this->operator)
            ->setFilters($filters2);

        $filters
            ->addFilter($filter)
            ->addFilter($filter2);

        $advanced
            ->setOffset($this->offset)
            ->setLimit($this->limit)
            ->setOrderBy('')
            ->setOrderDir($this->orderDir)
            ->setFullResponse($this->fullResponse)
            ->setFilters($filters);

        $userSearch->setAdvanced($advanced);

        $request->setCredentials($credentials);
        $request->setUserSearch($userSearch);

        return $this->serializer->serialize($request, 'xml');
    }

    /**
     * @return string
     */
    private function getRequestBody()
    {
        return '<SsoRequest>
            <Credentials>
                <ServiceProvider>
                    <ServiceToken><![CDATA[' . $this->serviceToken . ']]></ServiceToken>
                    <ServiceName><![CDATA[' . $this->serviceName . ']]></ServiceName>
                </ServiceProvider>
                <ServiceTrigger>
                    <UserIdentifier><![CDATA[' . $this->userIdentifier . ']]></UserIdentifier>
                    <Username><![CDATA[' . $this->username . ']]></Username>
                </ServiceTrigger>
                <ServiceCountry>
                    <Code><![CDATA[' . $this->langCode . ']]></Code>
                </ServiceCountry>
            </Credentials>
            <UserSearch>
                <Advanced>
                    <Offset>' . $this->offset . '</Offset>
                    <Limit>' . $this->limit . '</Limit>
                    <OrderBy><![CDATA[]]></OrderBy>
                    <OrderDir><![CDATA[' . $this->orderDir . ']]></OrderDir>
                    <FullResponse>' . $this->fullResponse . '</FullResponse>
                    <Filters>
                      <Filter>
                          <Strategy><![CDATA[' . $this->strategy . ']]></Strategy>
                          <Operator><![CDATA[' . $this->operator . ']]></Operator>
                          <UserType>
                              <Guid><![CDATA[' . $this->guid . ']]></Guid>
                              <Email><![CDATA[' . $this->email . ']]></Email>
                              <Username><![CDATA[' . $this->username . ']]></Username>
                              <Firstname><![CDATA[' . $this->firstName . ']]></Firstname>
                              <Lastname><![CDATA[' . $this->lastName . ']]></Lastname>
                              <Active>' . $this->active . '</Active>
                              <Deleted>' . $this->deleted . '</Deleted>
                              <MfaEnabled>' . $this->mfaEnabled . '</MfaEnabled>
                              <CreatedAt><![CDATA[' . $this->date . ']]></CreatedAt>
                              <UpdatedAt><![CDATA[' . $this->date . ']]></UpdatedAt>
                          </UserType>
                      </Filter>
                      <Filter>
                            <Strategy><![CDATA[' . $this->strategy . ']]></Strategy>
                            <Operator><![CDATA[' . $this->operator . ']]></Operator>
                            <Filters>
                                <Filter>
                                    <Strategy><![CDATA[' . $this->strategy . ']]></Strategy>
                                    <Operator><![CDATA[' . $this->operator . ']]></Operator>
                                    <ApplicationType>
                                        <Name><![CDATA[' . $this->name . ']]></Name>
                                        <Active>' . $this->active . '</Active>
                                        <AttributeType>
                                            <Name><![CDATA[' . $this->name . ']]></Name>
                                            <Value>' . $this->attrValue . '</Value>
                                            <Active>' . $this->active . '</Active>
                                        </AttributeType>
                                    </ApplicationType>
                                </Filter>
                            </Filters>
                        </Filter>
                    </Filters>
                </Advanced>
            </UserSearch>
        </SsoRequest>';
    }

    public function testGetterUserSearch()
    {
        /** @var  Request $requestModel */
        $requestModel = $this->serializer->deserialize(
            $this->setRequestBody(),
            Request::class,
            'xml'
        );

        $advanced = $requestModel->getUserSearch()->getAdvanced();
        $filter = $advanced->getFilters()->getFilter()[0];
        $userType = $filter->getUserType();
        $applicationType = $advanced->getFilters()->getFilter()[1]->getFilters()->getFilter()[0]->getApplicationType();
        $attributeType = $applicationType->getAttributeType();

        $credentials = $requestModel->getCredentials();

        $this->assertEquals($this->offset, $advanced->getOffset());
        $this->assertEquals($this->limit, $advanced->getLimit());
        $this->assertEquals('', $advanced->getOrderBy());
        $this->assertEquals($this->orderDir, $advanced->getOrderDir());
        $this->assertEquals($this->fullResponse, $advanced->getFullResponse());

        $this->assertEquals($this->strategy, $filter->getStrategy());
        $this->assertEquals($this->operator, $filter->getOperator());

        $this->assertEquals($this->guid, $userType->getGuid());
        $this->assertEquals($this->username, $userType->getUsername());
        $this->assertEquals($this->email, $userType->getEmail());
        $this->assertEquals($this->firstName, $userType->getFirstname());
        $this->assertEquals($this->lastName, $userType->getLastname());
        $this->assertEquals($this->active, $userType->getActive());
        $this->assertEquals($this->deleted, $userType->getDeleted());
        $this->assertEquals($this->mfaEnabled, $userType->getMfaEnabled());
        $this->assertEquals(new \DateTime($this->date), $userType->getCreatedAt());
        $this->assertEquals(new \DateTime($this->date), $userType->getUpdatedAt());

        $this->assertEquals($this->name, $applicationType->getName());
        $this->assertEquals($this->active, $applicationType->getActive());

        $this->assertEquals($this->name, $attributeType->getName());
        $this->assertEquals($this->attrValue, $attributeType->getValue());
        $this->assertEquals($this->active, $attributeType->getActive());

        $this->assertEquals($this->serviceToken, $credentials->getServiceProvider()->getServiceToken());
    }
}
