<?php
/**
 * LessCompiler class file.
 * @author Christoffer Niska <ChristofferNiska@gmail.com>
 * @copyright Copyright &copy; Christoffer Niska 2011-
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */

Yii::setPathOfAlias('Less', dirname(__FILE__).'/../lib/lessphp/lib/Less');

require dirname(__FILE__) . "/../lessc.inc.php";

class LessCompiler extends CApplicationComponent
{
	/**
	 * @var string the base path.
	 */
	public $basePath;
	/**
	 * @var array the paths for the files to parse.
	 */
	public $paths = array();
	/**
	 * @var boolean whether to automatically compile files.
	 */
	public $autoCompile = false;
	/**
	 * @var boolean compiler debug mode.
	 */
	public $debug = false;
	/**
	 * @var boolean whether to compress css or not.
	 */
	public $compress = false;

	protected $_parser;

	/**
	 * Initializes the component.
	 */
	public function init()
	{
		if ($this->basePath === null)
			$this->basePath = Yii::getPathOfAlias('webroot');

		if (!file_exists($this->basePath))
			throw new CException(__CLASS__.': '.Yii::t('less','Failed to initialize compiler. Base path does not exist!'));

		$this->_parser = new lessc;
		//$this->_parser->setFormatter("compressed");
	}
	
	public function compileFile($from, $to){
    	if (file_exists($from))
            file_put_contents($to, $this->parse($from));
        else
            throw new CException(__CLASS__.': '.Yii::t('less','Failed to compile less file. Source path does not exist!'));
	}

	/**
	 * Compiles the less files.
	 * @throws CException if the source path does not exist
	 */
	public function compile()
	{
		
		foreach ($this->paths as $lessPath => $cssPath)
		{
			
			$fromPath = $this->basePath.'/'.$lessPath;
			$toPath = $this->basePath.'/'.$cssPath;

			if (file_exists($fromPath))
				file_put_contents($toPath, $this->parse($fromPath));
			else
				throw new CException(__CLASS__.': '.Yii::t('less','Failed to compile less file. Source path does not exist!'));

		}
		
	}

	/**
	 * Parses the less code to css.
	 * @param string $filename the file path to the less file
	 * @return string the css
	 */
	public function parse($filename)
	{
		
		try
		{
			$css = $this->_parser->compileFile($filename);
		}
		catch (\Less\Exception\ParserException $e)
		{
			throw new CException(__CLASS__.': '.Yii::t('less','Failed to compile less file with message: `{message}`.',
					array('{message}'=>$e->getMessage())));
		}

		return $css;
	}
}
