<?php

namespace xo\cms;

use xo\content\ContentService;
use xo\cms\core\Configuration;

class MVCController {
	private $service;
	public function __construct(ContentService $service) {
		$this->service = $service;
	}
	public function isWebSiteOnline() {
		// FIXME
		return true;
	}
	function getCacheFile($path) {
		return Configuration::getInstance ()->getCacheDir () . $path;
	}
	function cacheExist($path, $since = null) {
		$cacheFile = $this->getCacheFile ();
		return file_exists ( $cacheFile );
	}
	function createCache($path) {
		$cacheFile = $this->getCacheFile ();
		if (file_exists ( $cacheFile )) {
			unlink ( $cacheFile );
		}
		$resource = $this->service->getResourceFromPath ( $path );
		if ($resource !== null && ! $resource->path->online) {
			if ($path != $resource->path->path) {
				header ( "Status: 301 Moved Permanently", false, 301 );
				header ( "Location: {$resource->path->path}" );
				exit ();
			} else {
				if ($resource instanceof WebPage) {
					$renderer = new WebPageRenderer ();
				} else {
					$renderer = new ResourceRenderer ( $this->service );
				}
				$renderer->render ( $cacheFile, $resource );
			}
		}
	}
	function renderCache($path, $out) {
		$cacheFile = Configuration::getInstance ()->getCacheDir () . "$path";
		//$md5 = base64_encode ( $resource->data->md5 );
		$date = gmdate ( "D, d M Y H:i:s", $resource->data->date ) . " GMT";
		//$expires = gmdate ( "D, d M Y H:i:s", time () + 3600 * 24 * 10 ) . " GMT";
		$expires = gmdate ( "D, d M Y H:i:s", time () + 3600   ) . " GMT";
		header ( "Cache-Control: max-age" );
		header ( "Expires: $expires" );
		header ( "Last-Modified: $date" );
		header ( "Date:$date" );
		// header ( "Content-Type:{$resource->data->contentType}" );
		// header ( "Content-Encoding:{$resource->data->encoding}" );
		// header ( "Content-Disposition:inline; filename={$resource->data->filename}" );
		//header ( "Content-MD5:$md5" );
	}
	function render($path, $out) {
		if ($this->isWebSiteOnline ()) {
			if (! $this->cacheExists ( $path )) {
				$this->createCache ( $path );
			}
			if ($this->cacheExists ( $path )) {
				$this->renderFromCache ( $path, $out );
			} else {
				$this->render404Error ( $out );
			}
		} else {
			$this->renderOffline ( $out );
		}
	}
	public function render404Error($out) {
		$renderer = new WebPageRenderer ();
		header ( 'Status: 404 Not Found', false, 404 );
		header ( 'Refresh:3;url=/' );
		$resource = new WebPage ();
		$resource->locale = "FR";
		$resource->templateName = "error-404";
		$resource->model = new WebPageModel ( $this->service, hex2bin ( "e2cf526e46f845b0a5e7cb8d66812238" ), hex2bin ( "2abb349c45534ee0b7d962e472d8d499" ) );
		$renderer->render ( $out, $resource );
	}
	public function renderOffline($out) {
		fwrite ( $out, "<html><head></head><body><main><h1>Offline !!!</h1></main></body></html>" );
	}
}

?>
