<?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 ObjectControllerTest 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/object/add');
        $this->assertTrue($crawler->filter('html:contains("Object - Add")')->count() > 0);
    }

    public function testShowSingle()
    {
        $this->logIn();
        $crawler = $this->client->request('GET', '/demo/object/showSingle');
        $this->assertTrue($crawler->filter('html:contains("Object - ShowSingle")')->count() > 0);
    }

    public function testShowMulti()
    {
        $this->logIn();
        $crawler = $this->client->request('GET', '/demo/object/showMulti');
        $this->assertTrue($crawler->filter('html:contains("Object - ShowMulti")')->count() > 0);
    }

    public function testTreeView()
    {
        $this->logIn();
        $crawler = $this->client->request('GET', '/demo/object/treeView');
        $this->assertTrue($crawler->filter('html:contains("Object - TreeView")')->count() > 0);
    }

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

    public function testDelete()
    {
        $this->logIn();
        $crawler = $this->client->request('GET', '/demo/object/delete');
        $this->assertTrue($crawler->filter('html:contains("Object - 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';
    }
}
