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

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

/**
 * ResponseTest
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */
class ResponseTest extends WebTestCase
{
    const FORMAT_JSON = 'json';

    /**
     * @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(static::FORMAT_JSON),
            $this->getResponseModel(static::FORMAT_JSON)
        );
    }

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

    public function testWrongResponseJSONModel()
    {
        $this->assertJsonStringEqualsJsonString(
            $this->getWrongResponse(static::FORMAT_JSON),
            $this->getWrongResponseModel(static::FORMAT_JSON)
        );
    }

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

    public function testGetterSuccess()
    {
        /** @var  RestResponse $responseModel */
        $responseModel = $this->serializer->deserialize(
            $this->getSuccessResponse(static::FORMAT_JSON),
            RestResponse::class,
            static::FORMAT_JSON
        );
        $this->assertEquals(200, $responseModel->getCode());
        $this->assertEquals('OK', $responseModel->getStatus());
        $this->assertEquals(0.01, $responseModel->getScriptTimeSec());
        $this->assertEquals('0000000000', $responseModel->getTrackId());
        $this->assertEquals(new \DateTime('2099-01-01T00:00:00+00:00'), $responseModel->getDate());

        foreach ($responseModel->getUserType() as $userType) {
            $this->assertEquals(200, $userType->getCode());
            $this->assertEquals('OK', $userType->getStatus());
            $this->assertEquals('0f8acee4d3488e0a21ceb1c7fa347131', $userType->getGuid());
            $this->assertEquals('testuser', $userType->getUsername());
            $this->assertEquals('user@domain.tld', $userType->getEmail());
            $this->assertEquals('Tester', $userType->getFirstName());
            $this->assertEquals('Testuser', $userType->getLastName());
            $this->assertEquals('Testuser', $userType->getLastName());
            $this->assertEquals(1, $userType->getActive());
            $this->assertEquals('24446666688888889', $userType->getAuthId());
            break;
        }
    }

    public function testSetterError()
    {
        $responseErrorModel = new RestResponse();

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

        $error = new ErrorCollector\Error();
        $error->setCode(400);
        $error->setMessage('ErrorMessage');

        $userType->setError($error);
        $responseErrorModel->addUserType($userType);
        $this->assertXmlStringEqualsXmlString(
            $this->serializer->serialize($responseErrorModel, "xml"),
            $this->getSimpleErrorXml()
        );
    }

    public function testGetterError()
    {
        /** @var  RestResponse $responseModel */
        $responseModel = $this->serializer->deserialize(
            $this->getErrorResponse(static::FORMAT_JSON),
            RestResponse::class,
            static::FORMAT_JSON
        );
        $this->assertEquals(400, $responseModel->getCode());
        $this->assertEquals('Bad Request', $responseModel->getStatus());
        $this->assertEquals(1.00, $responseModel->getScriptTimeSec());
        $this->assertEquals('4711', $responseModel->getTrackId());
        $this->assertEquals(new \DateTime('2016-10-31T14:40:30+01:00'), $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('ErrorCode: u10 ErrorRef: v001 ShortMessage: Invalid email-address',
                    $error->getMessage());
                $this->assertEquals('external', $error->getException());
            }
            break;
        }
    }

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

        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>
                        <authId><![CDATA[24446666688888889]]></authId>
                    </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,
                  "authId": "24446666688888889"
                }
              ]
            }';
        }
    }

    /**
     * @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": []
                }';
        }
    }

    /**
     * @return string
     */
    private function getErrorResponse($type = 'json')
    {
        if ($type === 'xml') {
            return '<?xml version="1.0" encoding="UTF-8"?>
                      <userAdd>
                          <code>400</code>
                          <status><![CDATA[Bad Request]]></status>
                          <trackId><![CDATA[4711]]></trackId>
                          <date><![CDATA[2016-10-31T14:40:30+01:00]]></date>
                          <scriptTimeSec>1.00</scriptTimeSec>
                          <users>
                              <userType>
                                  <code>400</code>
                                  <status><![CDATA[Bad Request]]></status>
                                  <errors>
                                      <error>
                                          <code>400</code>
                                          <message><![CDATA[ErrorCode: u10 ErrorRef: v001 ShortMessage: Invalid email-address]]></message>
                                          <exception><![CDATA[external]]></exception>
                                      </error>
                                  </errors>
                              </userType>
                          </users>
                      </userAdd>';
        } else {
            return '{
                      "code": 400,
                      "status": "Bad Request",
                      "trackId": "4711",
                      "date": "2016-10-31T14:40:30+01:00",
                      "scriptTimeSec": 1.00,
                      "users": [
                          {
                              "code": 400,
                              "status": "Bad Request",
                              "errors": [
                                  {
                                  "code": 400,
                                  "message": "ErrorCode: u10 ErrorRef: v001 ShortMessage: Invalid email-address",
                                  "exception": "external"
                                  }
                              ]
                          }
                      ]
                  }';
        }
    }

    public function getSimpleErrorXml()
    {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
                <userAdd>
                  <code>400</code>
                  <status><![CDATA[Bad Request]]></status>
                  <users>
                    <userType>
                      <code>400</code>
                      <status><![CDATA[Bad Request]]></status>
                      <errors>
                        <error>
                          <code>400</code>
                          <message><![CDATA[ErrorMessage]]></message>
                        </error>
                      </errors>
                    </userType>
                  </users>
                </userAdd>";
    }
}
