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

use Sso\RestBundle\ModelRest\Request\UserWs\Version2\UserSearch\Advanced\AdvancedSearch;
use Sso\RestBundle\ModelRest\Request\UserWs\Version2\UserSearch\Advanced\Request;
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\ModelShared\Request\UserWs\Version2\UserSearch\Advanced\ApplicationType;
use Sso\RestBundle\ModelShared\Request\UserWs\Version2\UserSearch\Advanced\AttributeType;
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 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 $username;

    /**
     * @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;

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

    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->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);
        $this->description = $this->faker->sentence();
    }

    public function testJsonSerialize()
    {
        $this->assertJsonStringEqualsJsonString($this->getRequestBody('json'), $this->setRequestBody('json'));
    }

    public function testXmlSerialize()
    {
        $this->assertXmlStringEqualsXmlString($this->getRequestBody('xml'), $this->setRequestBody('xml'));
    }

    /**
     * @param string $type (xml | json)
     * @return string
     */
    private function setRequestBody($type = 'xml')
    {
        $request = new Request();
        $advancedSearch = new AdvancedSearch();
        $filters = new Filters();
        $filters2 = new Filters();
        $filter = new Filter();
        $filter2 = new Filter();
        $filter3 = new Filter();
        $userType = new UserType();
        $applicationType = new ApplicationType();
        $attributeType = new AttributeType();

        // 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);

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

        $request->setAdvancedSearch($advancedSearch);

        return $this->serializer->serialize($request, ($type !== 'json' ? 'xml' : 'json'));
    }

    /**
     * @param string $type (xml | json)
     * @return string
     */
    private function getRequestBody($type = 'xml')
    {
        if ($type === 'json') {
            return '{
              "advancedSearch": {
                "offset": ' . $this->offset . ',
                "limit": ' . $this->limit . ',
                "orderBy": "",
                "orderDir": "' . $this->orderDir . '",
                "fullResponse": ' . $this->fullResponse . ',
                "filters": {
                    "Filter": [
                        {
                            "Strategy": "' . $this->strategy . '",
                            "Operator": "' . $this->operator . '",
                            "UserType": {
                               "Guid": "' . $this->guid . '",
                               "Email": "' . $this->email . '",
                               "Username": "' . $this->username . '",
                               "Firstname": "' . $this->firstName . '",
                               "Lastname": "' . $this->lastName . '",
                               "Active": ' . $this->active . ',
                               "Deleted": ' . $this->deleted . ',
                               "MfaEnabled": ' . $this->mfaEnabled . ',
                               "CreatedAt": "' . $this->date . '",
                               "UpdatedAt": "' . $this->date . '"
                            }
                        },
                        {
                            "Strategy": "' . $this->strategy . '",
                            "Operator": "' . $this->operator . '",
                            "Filters": {
                                "Filter": [
                                    {
                                        "Strategy": "' . $this->strategy . '",
                                        "Operator": "' . $this->operator . '",
                                        "ApplicationType": {
                                            "Name": "' . $this->name . '",
                                            "Active": ' . $this->active . ',
                                            "AttributeType": {
                                                "Name": "' . $this->name . '",
                                                "Value": "' . $this->attrValue . '",
                                                "Active": ' . $this->active . '
                                            }
                                        }
                                    }
                                ]
                            }
                        }
                    ]
                }
              }
            }';
        } else {
            return '<userSearchAdvanced>
                <advancedSearch>
                   <offset>' . $this->offset . '</offset>
                   <limit>' . $this->limit . '</limit>
                   <orderBy></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><![CDATA[' . $this->active . ']]></Active>
                                       <AttributeType>
                                           <Name><![CDATA[' . $this->name . ']]></Name>
                                           <Value><![CDATA[' . $this->attrValue . ']]></Value>
                                           <Active><![CDATA[' . $this->active . ']]></Active>
                                       </AttributeType>
                                   </ApplicationType>
                               </Filter>
                           </Filters>
                       </Filter>
                   </filters>
                </advancedSearch>
            </userSearchAdvanced>';
        }
    }

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

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

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

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