<?php

class TestController extends \Tools\AController
{
	public $started = false;

	public function start()
	{
		$this->started = true;
	}
}

class TestController2 extends \Tools\AController
{
	public $started = false;
	public $params;

	public function __construct($c, $p)
	{
		parent::__construct($c, $p);
		$this->params = $p;
		if (isset($p[":testId"]) && $p[":testId"] == "notFound")
			throw new \Exception\Error404();
	}

	public function start()
	{
		$this->started = true;
	}

	public function getId()
	{
		if (!isset($this->params[":testId"]))
			return false;
		return $this->params[":testId"];
	}
}

class ContextTest extends PHPUnit_Framework_TestCase
{
	public function testContext()
	{
		list($server, $mysqlConfig) = require("test/config.php");
		$dbh = new PDO($mysqlConfig[4][0], $mysqlConfig[1], $mysqlConfig[2]);
		$dbh->exec("DROP DATABASE ".$mysqlConfig[4][1]);
		$dbh->exec("CREATE DATABASE ".$mysqlConfig[4][1]);

		\Entity\ModelBase::init($mysqlConfig);
		// Double init test
		\Entity\ModelBase::init();
		$context = new \Tools\Context($server, false);
		\Entity\ModelBase::setup();
		$route = new \Entity\Cms();
		$route->shurl = "/testController0";
		$route->controller = "\TestController";
		$route->order = 0;
		$route->save();
		$this->assertNotNull($route->id);
		$this->assertNotFalse($route->id);
		$route = new \Entity\Cms();
		$route->shurl = "/test/:testId";
		$route->controller = "\TestController2";
		$route->order = 0;
		$route->save();
		$this->assertNotNull($route->id);
		$this->assertNotFalse($route->id);

		$this->assertEquals("127.0.0.10", $context->ip);
		$this->assertEquals($context, \Tools\Context::getContext());
		try {
			$i = $context->undefinedAttribute;
			$this->fail("Expected exception");
		}
		catch (\Exception $e)
		{ }
		$server["REQUEST_URI"] = "/testController0";
		$context = new \Tools\Context($server, false);
		$context->serve();
		$myController = $context->controller;
		$this->assertNotNull($myController);
		$this->assertInstanceOf("\TestController", $myController);
		$this->assertFalse($myController->started);

		$server["REQUEST_URI"] = "/";
		$context = new \Tools\Context($server, false);
		$context->serve();
		$myController = $context->controller;
		$this->assertNotNull($myController);
		$this->assertInstanceOf("\Controller\HomeController", $myController);

		$server["REQUEST_URI"] = "/test/notFound";
		$context = new \Tools\Context($server, false);
		$context->serve();
		$myController = $context->controller;
		$this->assertNotNull($myController);
		$this->assertInstanceOf("\Controller\Error404", $myController);
	}
}

