<?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\UserSearch\FindByApplicationRole;

use Sso\RestBundle\Api;
use Sso\RestBundle\ModelRest\Response\UserWs\Version2\UserSearch\FindByApplicationRole\Response as RestResponse;
use Sso\RestBundle\ModelRest\Response\UserWs\Version2\UserSearch\FindByApplicationRole\UserByRole;
use Sso\RestBundle\ModelRest\Response\UserWs\Version2\UserSearch\FindByApplicationRole\UserType;
use Sso\RestBundle\ModelXml\Response\UserWs\Version2\UserSearch\FindByApplicationRole\Success\UserType as XmlUserType;
use Doctrine\Common\Collections\ArrayCollection;
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 integer
     */
    private $active;

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

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

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

    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->active = $this->faker->boolean ? 1 : 0;
        $this->guid = $this->faker->md5;
        $this->username = $this->faker->userName;
        $this->email = $this->faker->email;
    }

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

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

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

    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->getUserByRole()->getUserType() as $userType) {
            $this->assertEquals(200, $userType->getCode());
            $this->assertEquals('OK', $userType->getStatus());
            $this->assertEquals($this->guid, $userType->getGuid());
            $this->assertEquals($this->email, $userType->getEmail());
            $this->assertEquals($this->username, $userType->getUsername());
            $this->assertEquals($this->active, $userType->getActive());

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

        $userTypes = new ArrayCollection();
        $userTypes->add($userType);

        $userByRole = new UserByRole();
        $userByRole->setUserType($userTypes);

        $responseErrorModel->setUserByRole($userByRole);

        $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->getUserByRole()->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
     * @param bool $variant
     * @return string
     */
    private function getResponseModel($type = 'json', $variant = false)
    {
        $response = new RestResponse();
        $response
            ->setCode(200)
            ->setStatus('OK')
            ->setTrackId($this->trackId)
            ->setDate(new \DateTime($this->date))
            ->setScriptTimeSec($this->scriptTimeSec);

        $response->setUserByRole($this->getUserByRole($variant));
        $responseModel = $this->serializer->serialize($response, $type);

        return $responseModel;
    }

    /**
     * @param bool $variant
     * @return UserByRole
     */
    private function getUserByRole($variant = false)
    {
        $userByRole = new UserByRole();

        if ($variant) {
            $userType = new XmlUserType();
        } else {
            $userType = new UserType();

            $userType
                ->setCode(200)
                ->setStatus('OK');
        }

        $userType
            ->setGuid($this->guid)
            ->setEmail($this->email)
            ->setUsername($this->username)
            ->setActive($this->active);

        $userTypes = new ArrayCollection();
        $userTypes->add($userType);

        $userByRole->setUserType($userTypes);

        if ($variant) {
            foreach ($userByRole->getUserType() as $userType) {
                $userType->setCode(200);
            }
        }

        return $userByRole;
    }

    /**
     * @param string $type
     * @return string
     */
    private function getSuccessResponse($type = 'json')
    {
        if ($type === 'xml') {
            return '<?xml version="1.0" encoding="UTF-8"?>
                <userSearchByRole>
                  <code>200</code>
                  <status><![CDATA[OK]]></status>
                  <trackId><![CDATA[' . $this->trackId . ']]></trackId>
                  <date><![CDATA[' . $this->date . ']]></date>
                  <scriptTimeSec>' . $this->scriptTimeSec . '</scriptTimeSec>
                  <userByRole>
                    <userType>
                        <code>200</code>
                        <status><![CDATA[OK]]></status>
                        <guid><![CDATA[' . $this->guid . ']]></guid>
                        <email><![CDATA[' . $this->email . ']]></email>
                        <username><![CDATA[' . $this->username . ']]></username>
                        <active>' . $this->active . '</active>
                    </userType>
                  </userByRole>
                </userSearchByRole>';
        } else {
            return '{
              "code": 200,
              "status": "OK",
              "trackId": "' . $this->trackId . '",
              "date": "' . $this->date . '",
              "scriptTimeSec": ' . $this->scriptTimeSec . ',
              "userByRole": {
                "userType": [
                    {
                      "code": 200,
                      "status": "OK",
                      "guid": "' . $this->guid . '",
                      "email": "' . $this->email . '",
                      "username": "' . $this->username . '",
                      "active": ' . $this->active . '
                    }
                ]
              }
            }';
        }
    }

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