<?php

namespace Sso\DemoBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

class TypeControllerTest extends WebTestCase
{

    /**
     * @var \Symfony\Bundle\FrameworkBundle\Client
     */
    protected $client = null;

    /**
     * Create client
     */
    public function setUp()
    {
        parent::setUp();
        $this->client = static::createClient();
    }

    public function testAdd()
    {
        $this->logIn();
        $crawler = $this->client->request('GET', '/demo/type/add');
        $this->assertTrue($crawler->filter('html:contains("Type - Add")')->count() > 0);
    }

    public function testShow()
    {
        $this->logIn();
        $crawler = $this->client->request('GET', '/demo/type/show');
        $this->assertTrue($crawler->filter('html:contains("Type - Show")')->count() > 0);
    }

    public function testUpdate()
    {
        $this->logIn();
        $crawler = $this->client->request('GET', '/demo/type/update');
        $this->assertTrue($crawler->filter('html:contains("Type - Update")')->count() > 0);
    }

    public function testDelete()
    {
        $this->logIn();
        $crawler = $this->client->request('GET', '/demo/type/delete');
        $this->assertTrue($crawler->filter('html:contains("Type - Delete")')->count() > 0);
    }

    /**
     * Simulate login
     */
    private 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
     */
    private function getFirewall()
    {
        return 'main';
    }
}
