<?php
class ToolRenderEmail extends AppModel {

	/**
	 * Get the expression for the template.
	 *
	 * @param 	string	$template	The template to get the expression for.
	 *
	 * @return	string	The expression for template, or empty string if not found.
	 */
	public function getExpressionForTemplate($template) {
		$item = $this->find('first', [
			'fields' => [
				'expression' ],
			'conditions' => [
				'name' => $template ]
		]);

		return $item ? $item[$this->alias]['expression'] : '';
	}

	/**
	 * Write the expression for the template.4
	 *
	 * @param 	string	$template	The template to write the expression to.
	 * @param	string	$expression	The expression for template.
	 *
	 * @return	mixed	The result of save method.
	 */
	public function write($template, $expression) {

		# Find existing
		$item = $this->find('first', [
			'fields' => [
				'id' ],
			'conditions' => [
				'name' => $template ]
		]);

		# Save
		$this->create();
		return $this->save([
			'id' => !empty($item) ? $item[$this->alias]['id'] : null,
			'name' => $template,
			'expression' => $expression
		]);
	}

}
