<?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\User\Add;

use Sso\RestBundle\Api;
use Sso\RestBundle\ModelRest\Common\Response\UserWs\ErrorCollector\Error;
use Sso\RestBundle\ModelRest\Response\UserWs\Version2\User\Add\Response as RestResponse;
use Sso\RestBundle\ModelRest\Response\UserWs\Version2\User\Add\UserType;
use GuzzleHttp\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;

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

    protected function setUp()
    {
        $this->client = static::createClient();
        $this->container = $this->client->getContainer();
        $this->apiM = new Api\Manager($this->container);
        $this->serializer = $this->apiM->serializer();
    }

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

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

    public function testWrongResponseJSONModel()
    {
        $this->assertJsonStringEqualsJsonString($this->getWrongResponse('json'), $this->getWrongResponseModel('json'));
    }

    public function testWrongResponseXMLModel()
    {
        $this->assertXmlStringEqualsXmlString($this->getWrongResponse('xml'), $this->getWrongResponseModel('xml'));
    }

    /**
     * @param string $type
     * @return string
     */
    private function getResponseModel($type = 'json')
    {
        $response = new RestResponse();
        $response
            ->setCode(200)
            ->setScriptTimeSec(0.01)
            ->setTrackId('0000000000')
            ->setDate(new \DateTime('2099-01-01T00:00:00+00:00'));
        $response->addUserType($this->getUserType());
        $responseModel = $this->serializer->serialize($response, $type);

        return $responseModel;
    }

    /**
     * @param string $type
     * @return string
     */
    private function getWrongResponseModel($type = 'json')
    {
        $response = new RestResponse();
        $response
            ->setCode(12)
            ->setScriptTimeSec(0.01)
            ->setTrackId('0000000000')
            ->setDate(new \DateTime('2099-01-01T00:00:00+00:00'));
        $responseModel = $this->serializer->serialize($response, $type);

        return $responseModel;
    }

    /**
     * @return UserType
     */
    private function getUserType()
    {
        $userType = new UserType();
        $userType->setCode(200);
        $userType
            ->setGuid('0f8acee4d3488e0a21ceb1c7fa347131')
            ->setUsername('testuser')
            ->setEmail('user@domain.tld')
            ->setFirstName('Tester')
            ->setLastName('Testuser')
            ->setActive(1)
            ->setAuthId('24446666688888889');
        $userType
            ->setDeleted(0)
            ->setMfaEnabled(1)
            ->setCreatedAt(new \DateTime('2099-01-01T00:00:00+00:00'))
            ->setUpdatedAt(new \DateTime('2099-01-01T00:00:00+00:00'));

        return $userType;
    }

    /**
     * @return string
     */
    private function getSuccessResponse($type = 'json')
    {
        if ($type === 'xml') {
            return '<?xml version="1.0" encoding="UTF-8"?>
                <userAdd>
                  <code>200</code>
                  <status><![CDATA[OK]]></status>
                  <trackId><![CDATA[0000000000]]></trackId>
                  <date><![CDATA[2099-01-01T00:00:00+00:00]]></date>
                  <scriptTimeSec>0.01</scriptTimeSec>
                  <users>
                    <userType>
                        <code>200</code>
                        <status><![CDATA[OK]]></status>
                        <guid><![CDATA[0f8acee4d3488e0a21ceb1c7fa347131]]></guid>
                        <username><![CDATA[testuser]]></username>
                        <email><![CDATA[user@domain.tld]]></email>
                        <firstname><![CDATA[Tester]]></firstname>
                        <lastname><![CDATA[Testuser]]></lastname>
                        <active>1</active>
                        <deleted>0</deleted>
                        <createdAt><![CDATA[2099-01-01T00:00:00+00:00]]></createdAt>
                        <updatedAt><![CDATA[2099-01-01T00:00:00+00:00]]></updatedAt>
                        <authId><![CDATA[24446666688888889]]></authId>
                        <mfaEnabled>1</mfaEnabled>
                    </userType>
                  </users>
                </userAdd>';
        } else {
            return '{
              "code": 200,
              "status": "OK",
              "trackId": "0000000000",
              "date": "2099-01-01T00:00:00+00:00",
              "scriptTimeSec": 0.01,
              "users": [
                {
                  "code": 200,
                  "status": "OK",
                  "guid": "0f8acee4d3488e0a21ceb1c7fa347131",
                  "username": "testuser",
                  "email": "user@domain.tld",
                  "firstname": "Tester",
                  "lastname": "Testuser",
                  "active": 1,
                  "deleted": 0,
                  "createdAt": "2099-01-01T00:00:00+00:00",
                  "updatedAt": "2099-01-01T00:00:00+00:00",
                  "authId": "24446666688888889",
                  "mfaEnabled": 1
                }
              ]
            }';
        }
    }

    /**
     * @return string
     */
    private function getWrongResponse($type = 'json')
    {
        if ($type === 'xml') {
            return '<?xml version="1.0" encoding="UTF-8"?>
                <userAdd>
                  <code>500</code>
                  <status><![CDATA[Internal Server Error]]></status>
                  <trackId><![CDATA[0000000000]]></trackId>
                  <date><![CDATA[2099-01-01T00:00:00+00:00]]></date>
                  <scriptTimeSec>0.01</scriptTimeSec>
                </userAdd>';
        } else {
            return '{
                "code": 500,
                "status": "Internal Server Error",
                "trackId": "0000000000",
                "date": "2099-01-01T00:00:00+00:00",
                "scriptTimeSec": 0.01,
                "users": []
                }';
        }
    }

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

        $userType = $responseModel->getUserType()->get(0);

        $error = new Error();
        $error->setCode(400)->setMessage('Example message')->setException('external');
        $userType->setError($error);

        $errors = $userType->getError();
        $errorResponse = $errors->get(0);

        $this->assertEquals(0, $userType->getDeleted());
        $this->assertEquals(new \DateTime('2099-01-01T00:00:00+00:00'), $userType->getCreatedAt());
        $this->assertEquals(new \DateTime('2099-01-01T00:00:00+00:00'), $userType->getUpdatedAt());
        $this->assertEquals(1, $userType->getMfaEnabled());
        $this->assertEquals(400, $errorResponse->getCode());
        $this->assertEquals('Example message', $errorResponse->getMessage());
        $this->assertEquals('external', $errorResponse->getException());
    }
}
