<?php

namespace modules\output;

// Create an object that will be used to create output
// stops here for txt,csv,json formats
// continues to theme modules for html
// registerview

class main extends \moduleMain {

	use traits {
			traits::__construct as __ConstructOutput;
		}

	public function __construct() {
		parent::__construct(__DIR__);
		$this->__ConstructOutput();
	}
	
	public function Activate() {
		hook_add('uri', [$this, '__doctype'], 40);
		hook_add('html.head', [$this, '__include']);
		
	// install function to handle document formats
		$this->Register_FormatHandler('csv', [$this, '__export_csv'], 'simple Comma Separated Values');
		$this->Register_FormatHandler('json', [$this, '__export_json'], 'JavaScript Object Notation');
		$this->Register_FormatHandler('serial', [$this, '__export_serial'], 'Designed for use with PHP');
		$this->Register_FormatHandler('xml', [$this, '__export_xml'], 'Extensible Markup Language');
		$this->Register_FormatHandler('txt', [$this, '__export_txt'], 'Generic text format');
	}

	// set a default doc type based on extension
	//   don't set if no compatible ext found
	public function __doctype(&$uri, $input) {
		$ok = FALSE;
		$query = ($p = strpos($uri, '?')) !== FALSE ? substr($uri, $p) : '';
		if ($query != '') $uri = substr($uri, 0, $p);
		
		$elements = explode('/', $uri);
		for($i = count($elements) - 1; $i >= 0; $i--) {
			list($name, $ext) = $this->__OUTPUT->getRecognizedExtension($elements[$i]);
			if ($ext !== FALSE) {
				$elements[$i] = $name;
				$this->OutputFormat($ext);
				$ok = TRUE;
				break;
			}
		}
		$uri = implode('/', $elements);
		$uri .= $query;
		if (!$ok) $this->_checkAccept($input);		// no extension found - are we after a specific document type?
	}
	
	private function _checkAccept($input) {
		$mimetype = $input->GetPreferedDocType();
		if ($mimetype == 'application/json' ||
			$mimetype == 'text/javascript') {
				$this->OutputFormat('json');
		}
	}
	
	public function __include(&$html) {
		$html .= $this->GetInclude();
	}

	private function _lv($name, $data) {
		$view = $this->loadView(__DIR__, $name);
		return $view->render($data);
	}

	public function __export_json($data) {
		return $this->_lv('export_json', $data);
	}

	public function __export_csv($data) {
		return $this->_lv('export_csv', $data);
	}

	public function __export_txt($data) {
		return $this->_lv('export_txt', $data);
	}

	public function __export_serial($data) {
		return $this->_lv('export_serial', $data);
	}
	public function __export_xml($data) {
		return $this->_lv('export_xml', $data);
	}
	
	// convert less file to css
	final function css() {
		$param = func_get_args();
		$model = $this->LoadModel('output_model');
		echo $model->ConvertLESStoCSS($param);
		exit;
	}

}