<?php

/**
 * Class WebserviceTestCase
 *
 * 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\Webservices\ObjectBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Sso\ApiBundle\Api\Manager as ApiManager;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

/**
 * Class WebserviceTestCase
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\Webservices\ObjectBundle\Tests\Controller
 */
class WebserviceTestCase extends WebTestCase
{

    /**
     * Webservice service token
     *
     * @var string
     */
    protected $ServiceToken = 'X2222cOhc6Vttcxs6r6bmtdlc8Z1ryTN1TQ16pjivEcprZhye9e17ba7508a4358f99c8ba52ded0f70RnZDhDyKMXLEWobXI2ZOrJ7mXjcPJJNk7wxoAw8WUTk0IMYa';

    /**
     * Webservice service name
     *
     * @var string
     */
    protected $ServiceName = 'MyService';

    /**
     * Webservice country code
     *
     * @var string
     */
    protected $ServiceCountryCode = 'DE';

    /**
     * Webservice user identifier
     *
     * @var string
     */
    protected $UserIdentifier = 'd5d827018ff721b76e154185512fc56e2194fe9cc7d0789fb1a827a004f4bdb082e7440f71fda9d047a09761447277ce6a52a1630506b49c48cd925bcf60e1d2';

    /**
     * @var Client $client
     */
    protected $client;

    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * Setup some defaults
     */
    protected function setUp()
    {
        parent::setUp();

        $this->client = static::createClient();
        $this->container = $this->client->getContainer();
        $this->client->setServerParameter('HTTP_HOST', $this->container->getParameter('test_client_host'));

        $this->loadFixtures();

        global $argv, $argc;
        if (0 < $argc && false !== ($idx = array_search('-useridentifier', $argv)) && $idx < $argc) {
            $this->UserIdentifier = $argv[$idx + 1];
        }
    }

    /**
     * Make Doctrine schema update and load fixtures
     */
    protected function loadFixtures()
    {
        $kernel = $this->container->get('kernel');
        $application = new Application($kernel);
        $application->setAutoExit(false);

        $options = array(
            'command' => 'doctrine:schema:update',
            '--force' => true,
            '--em' => 'Webservice',
            '-e' => 'test'
        );
        $application->run(new ArrayInput($options));
        $options = array('command' => 'doctrine:schema:update', '--force' => true, '--em' => 'Backend', '-e' => 'test');
        $application->run(new ArrayInput($options));
        $options = array(
            'command' => 'doctrine:schema:update',
            '--force' => true,
            '--em' => 'ServiceProvider',
            '-e' => 'test'
        );
        $application->run(new ArrayInput($options));

        $options = array(
            'command' => 'doctrine:fixtures:load',
            '--fixtures' => $this->apiM()->container->get('kernel')->getRootDir() . '/../src/Sso/Webservices/ObjectBundle/DataFixtures/ORM',
            '--no-interaction' => true,
            '--em' => 'Webservice',
            '-e' => 'test'
        );
        $application->run(new ArrayInput($options));
        $options = array(
            'command' => 'doctrine:fixtures:load',
            '--fixtures' => $this->apiM()->container->get('kernel')->getRootDir() . '/../src/LifeStyle/Tools/CredentialsBundle/DataFixtures/ORM',
            '--no-interaction' => true,
            '--em' => 'ServiceProvider',
            '-e' => 'test'
        );
        $application->run(new ArrayInput($options));
    }

    /**
     * Simulate login
     */
    protected function logIn()
    {
        $session = $this->client->getContainer()->get('session');

        $firewall = $this->getFirewall();
        $token = new UsernamePasswordToken('unittest', null, $firewall, array('ROLE_SUPER_ADMIN'));
        $session->set('_security_' . $firewall, serialize($token));
        $session->save();

        $cookie = new Cookie($session->getName(), $session->getId());
        $this->client->getCookieJar()->set($cookie);
    }

    /**
     * Get firewall name @see security.yml
     *
     * @return string
     */
    protected function getFirewall()
    {
        return 'main';
    }

    /**
     * Creates a new api manager
     *
     * @return ApiManager
     */
    protected function apiM()
    {
        return new ApiManager($this->container, $this->container->get('logger'));
    }

}