<?php

/*
 * @copyright NetMonsters <team@netmonsters.ru>
 * @link http://netmonsters.ru
 * @package Majestic
 * @subpackage UnitTests
 * @since 2011-11-1
 * 
 * Unit tests for FrontController class
 */

require_once dirname(__FILE__) . '/../../session/Session.php';
require_once dirname(__FILE__) . '/../../classes/Env.class.php';
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../util/FirePHPCore-0.3.2/lib/FirePHPCore/fb.php';
require_once dirname(__FILE__) . '/../../util/profiler/Profiler.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../exception/ErrorHTTPException.php';
require_once dirname(__FILE__) . '/../../exception/Error404Exception.php';
require_once dirname(__FILE__) . '/../../exception/ErrorHandler.php';
require_once dirname(__FILE__) . '/../../app/router/Route.php';
require_once dirname(__FILE__) . '/../../app/router/Router.php';
require_once dirname(__FILE__) . '/../../app/FrontController.php';
require_once dirname(__FILE__) . '/../../app/Action.php';
require_once dirname(__FILE__) . '/../../app/AjaxAction.php';

class FrontControllerTest extends PHPUnit_Framework_TestCase
{
    protected $log_file_name = 'error_log_file';

    public function run(PHPUnit_Framework_TestResult $result = NULL)
    {
        $this->setPreserveGlobalState(false);
        return parent::run($result);
    }

    public function setUp()
    {
        if (!class_exists('PHPViewMock')) {
            $this->getMock('PHPView', array('fetch', 'append', 'prepend', 'assign', 'getTemplate'), array(), 'PHPViewMock', false);
        }
        if (!class_exists('View')) {
            $this->getMock('View');
        }
        if (!class_exists('ErrorLayout')) {
            $this->getMock('ErrorLayout', array('fetch', 'setException'), array(), 'ErrorLayoutMock');
        }
        if (!class_exists('ErrorActionMock')) {
            $this->getMock('ErrorAction', array('setAjaxError'), array(), 'ErrorActionMock', false);
        }
        set_new_overload(array($this, 'newCallback'));
    }

    /**
     * @runInSeparateProcess
     */
    public function testGetInstanceNoProfiler()
    {
        $this->setConstants(false);
        $controller = FrontController::getInstance();
        $this->assertAttributeEquals($controller, 'instance', 'FrontController');
    }

    /**
     * @runInSeparateProcess
     */
    public function testGetInstanceWithProfiler()
    {
        $this->setConstants(true);
        $controller = FrontController::getInstance();
        $this->assertAttributeEquals($controller, 'instance', 'FrontController');
    }

    /**
     * @runInSeparateProcess
     */
    public function testSetView()
    {
        $this->setConstants(false);
        $controller = FrontController::getInstance();
        $this->assertSame($controller, $controller->setView('View'));
    }

    /**
     * @runInSeparateProcess
     */
    public function testGetDefaultView()
    {
        $this->setConstants(false);
        $controller = FrontController::getInstance();
        $this->assertNotInstanceOf('View', $controller->getView());
        $this->assertInstanceOf('PHPView', $controller->getView());
    }

    /**
     * @runInSeparateProcess
     */
    public function testGetCustomView()
    {
        $this->setConstants(false);
        $controller = FrontController::getInstance();
        $this->assertInstanceOf('View', $controller->getView('View'));
    }

    /**
     * @runInSeparateProcess
     */
    public function testSetGetBaseUrl()
    {
        $this->setConstants(false);
        $controller = FrontController::getInstance();
        $this->assertSame('', $controller->getBaseUrl());
        $controller->setBaseUrl('/index/');
        $this->assertSame('/index', $controller->getBaseUrl());
    }

    /**
     * @runInSeparateProcess
     */
    public function testGetRouter()
    {
        $this->setConstants(false);
        $controller = FrontController::getInstance();
        $this->assertInstanceOf('Router', $controller->getRouter());
    }

    /**
     * @runInSeparateProcess
     */
    public function testExecuteNoRoute()
    {
        $this->setConstants(false);
        $controller = FrontController::getInstance();
        $this->assertNull($controller->execute());
    }

    /**
     * @runInSeparateProcess
     */
    public function testExecuteNoRouteDebug()
    {
        $this->setConstants(true);
        ini_set('error_log', $this->log_file_name);
        $controller = FrontController::getInstance();
        $result = $controller->execute();
        $this->assertNotEmpty($result);
        $this->assertContains('Route for "" not found', $result);
        $this->assertContains('Error404Exception', $result);
        $error = file_get_contents($this->log_file_name);
        $this->assertContains('PHP Unknown Error:  Error404Exception: Route for "" not found in ', $error);
    }

    /**
     * @runInSeparateProcess
     */
    public function testExecuteNoAction()
    {
        $_SERVER['REQUEST_URI'] = '/user/account/213';
        $this->setConstants(true);
        ini_set('error_log', $this->log_file_name);
        $controller = FrontController::getInstance();
        $router = $controller->getRouter();
        $router->add('user', 'user/account/:id', 'user');
        $result = $controller->execute();
        $this->assertContains('Action class "userAction" not found.', $result);
        $error = file_get_contents($this->log_file_name);
        $this->assertContains('PHP Unknown Error:  GeneralException: Action class "userAction" not found. in ', $error);
    }

    /**
     * @runInSeparateProcess
     */
    public function testExecuteNoLayout()
    {
        $this->getMock('userAction');
        $_SERVER['REQUEST_URI'] = '/user/account/213';
        $this->setConstants(true);
        ini_set('error_log', $this->log_file_name);
        $controller = FrontController::getInstance();
        $router = $controller->getRouter();
        $router->add('user', 'user/account/:id', 'user');
        $result = $controller->execute();
        $this->assertContains('Layout class "DefaultLayout" not found.', $result);
        $error = file_get_contents($this->log_file_name);
        $this->assertContains('PHP Unknown Error:  GeneralException: Layout class "DefaultLayout" not found. in ', $error);
    }

    /**
     * @runInSeparateProcess
     */
    public function testExecuteWithLayout()
    {
        $this->getMock('userAction');
        $this->getMock('DefaultLayout', array('fetch'), array(), 'DefaultLayoutMock');
        $_SERVER['REQUEST_URI'] = '/user/account/213';
        $this->setConstants(true);
        $controller = FrontController::getInstance();
        $router = $controller->getRouter();
        $router->add('user', 'user/account/:id', 'user');
        $result = $controller->execute();
        $this->assertNull($result);
    }

    /**
     * @runInSeparateProcess
     */
    public function testExecuteWithLayoutProfiler()
    {
        Config::set('PROFILER', true);
        $this->getMock('userAction');
        $this->getMock('DefaultLayout', array('fetch'), array(), 'DefaultLayoutMock');
        $_SERVER['REQUEST_URI'] = '/user/account/213';
        $this->setConstants(true);
        $controller = FrontController::getInstance();
        $router = $controller->getRouter();
        $router->add('user', 'user/account/:id', 'user');
        $result = $controller->execute();
        $this->assertNull($result);
    }

    /**
     * @runInSeparateProcess
     */
    public function testExecuteWithAjaxAction()
    {
        $this->getMock('userAction');
        $this->getMock('DefaultLayout', array('fetch'), array(), 'DefaultLayoutMock');
        $_SERVER['REQUEST_URI'] = '/user/account/213';
        $this->setConstants(true);
        $controller = FrontController::getInstance();
        $router = $controller->getRouter();
        $router->add('user', 'user/account/:id', 'NewAjax');
        $result = $controller->execute();
        $this->assertNull($result);
    }

    /**
     * @runInSeparateProcess
     */
    public function testExecuteWithAjaxActionError()
    {
        $this->getMock('userAction');
        $_SERVER['REQUEST_URI'] = '/user/account/213';
        $this->setConstants(false);
        $controller = FrontController::getInstance();
        $router = $controller->getRouter();
        $router->add('user', 'user/account/:id', 'NewAjax');
        $result = $controller->execute();
        $this->assertNull($result);
    }

    /**
     * @runInSeparateProcess
     */
    public function testExecuteWithAjaxActionProfiler()
    {
        Config::set('PROFILER', true);
        $this->getMock('userAction');
        $this->getMock('DefaultLayout', array('fetch'), array(), 'DefaultLayoutMock');
        $_SERVER['REQUEST_URI'] = '/user/account/213';
        $this->setConstants(true);
        $controller = FrontController::getInstance();
        $router = $controller->getRouter();
        $router->add('user', 'user/account/:id', 'NewAjax');
        $result = $controller->execute();
        $this->assertNull($result);
    }

    private function setConstants($val = false)
    {

        Config::set('DEBUG', $val);
    }

    public function tearDown()
    {
        unset_new_overload();
        if (file_exists($this->log_file_name) && is_writable($this->log_file_name)) {
            unlink($this->log_file_name);
        }
        ini_set('error_log', 'php://stderr');
    }

    protected function newCallback($className)
    {
        switch ($className) {
            case 'PHPView':
                return 'PHPViewMock';
            case 'DefaultLayout':
                return 'DefaultLayoutMock';
            case 'ErrorAction':
                return 'ErrorActionMock';
            case 'ErrorLayout':
                return 'ErrorLayoutMock';
            default:
                return $className;
        }
    }
}

/**
 * Used in testExecuteWithAjaxAction
 */
class NewAjaxAction extends AjaxAction
{
    protected function execute()
    {
    }
}