<?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);
		$context = new \Tools\Context($server, false);
		\Entity\ModelBase::setup();
		$route = new \Entity\Cms();
		$route->shurl = "/";
		$route->controller = "\TestController";
		$route->order = 0;
		$route->save();
		$this->assertEquals(1, $route->id);
		$route = new \Entity\Cms();
		$route->shurl = "/test/:testId";
		$route->controller = "\TestController2";
		$route->order = 0;
		$route->save();
		$this->assertEquals(2, $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)
		{ }
		$context->serve();
		$myController = $context->controller;
		$this->assertNotNull($myController);
		$this->assertInstanceOf("\TestController", $myController);
		$this->assertFalse($myController->started);

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

		$server["REQUEST_URI"] = "/test/42";
		$context = new \Tools\Context($server, false);
		$context->serve();
		$myController = $context->controller;
		$this->assertNotNull($myController);
		$this->assertInstanceOf("\TestController2", $myController);
		$this->assertEquals(42, (int) $myController->getId());

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

