<?php

class EditorController extends AppBackendController {

	var $uses = [];

	# Allow access to editor #
	function beforeFilter() {
		$this->layout = false;
		parent::beforeFilter();
		if ($this->Auth->user()) {
			$this->Auth->allow();
		}
	}

	# Get list of pages #
	function pages() {
		$this->set('pages', ClassRegistry::init('Page')->getNodeList());
	}

	# Get list of modules #
	function modules() {
		$modules = ClassRegistry::init('Module')->find('list', [ 'fields' => [ 'name', 'name' ] ]);
		foreach ($modules as $module) {
			$modules[$module] = preg_replace('/(.)([A-Z])/', '$1 $2', $module);
		}
		return $this->json($modules);
	}

	# Get list of module ordering #
	function module_ordering($name) {
		$module = ClassRegistry::init('Module')->generate($name, true);
		$fields = array_keys($module->getAvailableFields());
		return $this->json([
			'default' => [
				'field'     => lastFromDot(key($module->order)),
				'direction' => strtolower(reset($module->order)) ],
			'fields'  => $this->jsa($fields, false)
		]);
	}

	# Get list of the available fields #
	function fields($name) {
		$fields = [];
		$module = ClassRegistry::init('Module')->generate($name, true);
		/*foreach($module->hasOne as $association => $params) if($params['className'] == 'Upload') {
			$fields[$association] = 'single-upload';
		}
		foreach($module->hasMany as $association => $params) if($params['className'] == 'Upload') {
			$fields[$association] = 'multiple-upload';
		}*/
		foreach ($module->getAvailableFields() as $field => $params) {
			$fields[$field] = $params['type'];
		}
		return $this->json($fields);
	}
}
