<?php
class Layout extends AppModel {

	public $displayField = 'name';

	public $displayImage = null;

	public $tablePrefix = 'live_';
	public $actsAs = array(
		'Live' => array(
			'field' => 'body',
			'folder' => 'View/Layouts',
			'extension' => 'ctp')
	);

	public $validate = array(
		'name' => array(
			'notempty',
			'isUnique' => 'The layer name must be unique'
		)
	);

	public $formOptions = array(
		'body' => array(
			'rte' => false,
			'class' => 'cm-full',
			'style' => 'height:600px;font-family:Monospace,Courier New')
	);


# ~ Extracts all blocks found in the layout	 - - - - - - - - - - - - - - - - - #
	public function getBlocks($id = 'default') {

		# Get blocks of the default layout of from specific one
		$conditions = is_numeric($id)
			? array('Layout.id' => $id)
			: array('Layout.is_default' => true);

		$data = $this->find('first', array(
			'comment' => 'Get blocks found in layout',
			'fields' => array('Layout.body'),
			'recursive' => -1,
			'conditions' => $conditions
		));

		# Extract blocks from the layout
		$extracted = $this->parseDynamicTags($data['Layout']['body'], 'block');

		# Parse the result
		$blocks = array();
		if(!empty($extracted)) {
			foreach($extracted['params'] as $i => $param) {
				$blocks[$i] = array('order' => $i, 'type' => 'textarea');
				if(preg_match('~ (?<key>.+)\s*=\s*"(?<value>.*)"$~', $param, $match)) {
					$blocks[$i][$match['key']] = $match['value'];
				}

				# Set empty content for all languages
				foreach(Configure::read('Config.Languages') as $locale => $details) {
					$blocks[$i]['content'][$locale] = array();
				}

				# Make sure name params is set
				if(!empty($blocks[$i]['name'])) {
					$blocks[$blocks[$i]['name']] = $blocks[$i];
					unset($blocks[$blocks[$i]['name']]['name']);
				}
				unset($blocks[$i]);
			}
		}

		return $blocks;
	}


}
?>
