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

use Sso\RestBundle\Api;
use Sso\RestBundle\ModelRest\Response\UserWs\Version2\UserApplicationAttribute\Show\Response as RestResponse;
use Sso\RestBundle\ModelRest\Response\UserWs\Version2\UserApplicationAttribute\Show\UserType;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserApplicationAttribute\Show\Success\ApplicationType as XmlApplicationType;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserApplicationAttribute\Show\Success\AttributeType as XmlAttributeType;
use GuzzleHttp\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Sso\RestBundle\ModelRest\Common\Response\UserWs\ErrorCollector;
use Faker\Factory as FakerFactory;
use Faker\Generator as FakerGenerator;

/**
 * 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 string
     */
    private $trackId;

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

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

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

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

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

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

    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->trackId = $this->faker->md5;
        $this->date = '2099-01-01T00:00:00+00:00';
        $this->scriptTimeSec = $this->faker->randomFloat(2);
        $this->name = $this->faker->word;
        $this->description = $this->faker->sentence();
        $this->message = $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;
    }

    public function testResponseJSONModel()
    {
        $this->assertJsonStringEqualsJsonString(
            $this->getSuccessResponse('json'),
            $this->getResponseModel('json')
        );
    }

    public function testResponseXMLModel()
    {
        $this->assertXmlStringEqualsXmlString(
            $this->getSuccessResponse('xml'),
            $this->getResponseModel('xml')
        );
    }

    public function testGetterSuccess()
    {
        /** @var  RestResponse $responseModel */
        $responseModel = $this->serializer->deserialize(
            $this->getSuccessResponse('json'),
            RestResponse::class,
            'json'
        );

        $this->assertEquals(200, $responseModel->getCode());
        $this->assertEquals('OK', $responseModel->getStatus());
        $this->assertEquals($this->scriptTimeSec, $responseModel->getScriptTimeSec());
        $this->assertEquals($this->trackId, $responseModel->getTrackId());
        $this->assertEquals(new \DateTime($this->date), $responseModel->getDate());

        foreach ($responseModel->getUserType() as $userType) {
            $this->assertEquals(200, $userType->getCode());
            $this->assertEquals('OK', $userType->getStatus());
            $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(new \DateTime($this->date), $userType->getCreatedAt());
            $this->assertEquals(new \DateTime($this->date), $userType->getUpdatedAt());
            $this->assertEquals(new \DateTime($this->date), $userType->getLastLoginAt());
            $this->assertEquals($this->authId, $userType->getAuthId());
            $this->assertEquals('', $userType->getLdapSearchAttributes());
            $this->assertEquals('', $userType->getLdapSearchValue());
            $this->assertEquals($this->mfaEnabled, $userType->getMfaEnabled());

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

                foreach ($applicationType->getApplicationAttribute() as $applicationAttribute) {
                    $this->assertEquals($this->attrName, $applicationAttribute->getName());
                    $this->assertEquals($this->attrType, $applicationAttribute->getType());
                    $this->assertEquals($this->attrValue, $applicationAttribute->getValue());

                    break;
                }

                break;
            }

            break;
        }
    }

    public function testSetterError()
    {
        $responseErrorModel = new RestResponse();
        $responseErrorModel
            ->setCode(400)
            ->setScriptTimeSec($this->scriptTimeSec)
            ->setDate(new \DateTime($this->date))
            ->setTrackId($this->trackId);

        $userType = new UserType();
        $userType->setCode(400);

        $error = new ErrorCollector\Error();
        $error
            ->setCode(400)
            ->setMessage($this->message)
            ->setException('external');

        $userType->setError($error);
        $responseErrorModel->addUserType($userType);

        $this->assertJsonStringEqualsJsonString(
            $this->serializer->serialize($responseErrorModel, "json"),
            $this->getErrorResponse()
        );
    }

    public function testGetterError()
    {
        /** @var  RestResponse $responseModel */
        $responseModel = $this->serializer->deserialize(
            $this->getErrorResponse('json'),
            RestResponse::class,
            'json'
        );

        $this->assertEquals(400, $responseModel->getCode());
        $this->assertEquals('Bad Request', $responseModel->getStatus());
        $this->assertEquals($this->scriptTimeSec, $responseModel->getScriptTimeSec());
        $this->assertEquals($this->trackId, $responseModel->getTrackId());
        $this->assertEquals(new \DateTime($this->date), $responseModel->getDate());

        foreach ($responseModel->getUserType() as $userType) {
            $this->assertEquals(400, $userType->getCode());
            $this->assertEquals('Bad Request', $userType->getStatus());
            foreach ($userType->getError() as $error) {
                $this->assertEquals(400, $error->getCode());
                $this->assertEquals($this->message, $error->getMessage());
                $this->assertEquals('external', $error->getException());
            }
            break;
        }
    }

    /**
     * @param string $type
     * @return string
     */
    private function getResponseModel($type = 'json')
    {
        $response = new RestResponse();
        $response
            ->setCode(200)
            ->setStatus('OK')
            ->setTrackId($this->trackId)
            ->setDate(new \DateTime($this->date))
            ->setScriptTimeSec($this->scriptTimeSec);

        $response->addUserType($this->getUserType());
        $responseModel = $this->serializer->serialize($response, $type);

        return $responseModel;
    }

    /**
     * @return UserType
     */
    private function getUserType()
    {
        $userType = new UserType();
        $applicationType = new XmlApplicationType();
        $attributeType = new XmlAttributeType();

        $attributeType
            ->setName($this->attrName)
            ->setType($this->attrType)
            ->setValue($this->attrValue);

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

        $userType
            ->setCode(200)
            ->setStatus('OK');
        $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))
            ->setLastLoginAt(new \DateTime($this->date))
            ->setMfaEnabled($this->mfaEnabled)
            ->setApplicationType($applicationType);

        return $userType;
    }

    /**
     * @param string $type
     * @return string
     */
    private function getSuccessResponse($type = 'json')
    {
        if ($type === 'xml') {
            return '<?xml version="1.0" encoding="UTF-8"?>
                <userApplicationAttribute>
                  <code>200</code>
                  <status><![CDATA[OK]]></status>
                  <trackId><![CDATA[' . $this->trackId . ']]></trackId>
                  <date><![CDATA[' . $this->date . ']]></date>
                  <scriptTimeSec>' . $this->scriptTimeSec . '</scriptTimeSec>
                  <userApplicationAttributes>
                    <userType>
                        <code>200</code>
                        <status><![CDATA[OK]]></status>
                        <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>
                        <lastLoginAt><![CDATA[' . $this->date . ']]></lastLoginAt>
                        <authId><![CDATA[' . $this->authId . ']]></authId>
                        <mfaEnabled>' . $this->mfaEnabled . '</mfaEnabled>
                        <applicationType>
                            <name><![CDATA[' . $this->appName . ']]></name>
                            <active>' . $this->active . '</active>
                            <applicationAttribute>
                                <name><![CDATA[' . $this->attrName . ']]></name>
                                <type><![CDATA[' . $this->attrType . ']]></type>
                                <value><![CDATA[' . $this->attrValue . ']]></value>
                            </applicationAttribute>
                        </applicationType>
                    </userType>
                  </userApplicationAttributes>
                </userApplicationAttribute>';
        } else {
            return '{
              "code": 200,
              "status": "OK",
              "trackId": "' . $this->trackId . '",
              "date": "' . $this->date . '",
              "scriptTimeSec": ' . $this->scriptTimeSec . ',
              "userApplicationAttributes": [
                {
                  "code": 200,
                  "status": "OK",
                  "guid": "' . $this->guid . '",
                  "username": "' . $this->username . '",
                  "email": "' . $this->email . '",
                  "firstname": "' . $this->firstName . '",
                  "lastname": "' . $this->lastName . '",
                  "active": ' . $this->active . ',
                  "deleted": ' . $this->deleted . ',
                  "createdAt": "' . $this->date . '",
                  "updatedAt": "' . $this->date . '",
                  "lastLoginAt": "' . $this->date . '",
                  "authId": "' . $this->authId . '",
                  "mfaEnabled": ' . $this->mfaEnabled . ',
                  "applicationType": [
                    {
                      "name": "' . $this->appName . '",
                      "active": ' . $this->active . ',
                      "applicationAttribute": [
                          {
                              "name": "' . $this->attrName . '",
                              "type": "' . $this->attrType . '",
                              "value": "' . $this->attrValue . '"
                          }
                      ]
                    }
                  ]
                }
              ]
            }';
        }
    }

    /**
     * @param string $type
     * @return string
     */
    private function getErrorResponse($type = 'json')
    {
        if ($type === 'xml') {
            return '<?xml version="1.0" encoding="UTF-8"?>
                      <userApplicationAttribute>
                          <code>400</code>
                          <status><![CDATA[Bad Request]]></status>
                          <trackId><![CDATA[' . $this->trackId . ']]></trackId>
                          <date><![CDATA[' . $this->date . ']]></date>
                          <scriptTimeSec>' . $this->scriptTimeSec . '</scriptTimeSec>
                          <userApplicationAttributes>
                              <userType>
                                  <code>400</code>
                                  <status><![CDATA[Bad Request]]></status>
                                  <errors>
                                      <error>
                                          <code>400</code>
                                          <message><![CDATA[' . $this->message . ']]></message>
                                          <exception><![CDATA[external]]></exception>
                                      </error>
                                  </errors>
                              </userType>
                          </userApplicationAttributes>
                      </userApplicationAttribute>';
        } else {
            return '{
                      "code": 400,
                      "status": "Bad Request",
                      "trackId": "' . $this->trackId . '",
                      "date": "' . $this->date . '",
                      "scriptTimeSec": ' . $this->scriptTimeSec . ',
                      "userApplicationAttributes": [
                          {
                              "code": 400,
                              "status": "Bad Request",
                              "errors": [
                                  {
                                  "code": 400,
                                  "message": "' . $this->message . '",
                                  "exception": "external"
                                  }
                              ]
                          }
                      ]
                  }';
        }
    }
}
