<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS
 * @copyright Copyright (c) 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

require_once FLAPPPATH . 'lessphp/lessc.inc.php';

/**
 * cfLessc Class
 *
 * Class to extend the less compiler to support imports of documents.
 *
 * @package clearFusionCMS
 */
class cfLessc extends lessc {

	/**
	 * The conect access object.
	 *
	 * @var cfContent
	 */
	protected $content = null;

	/**
	 * @inheritdoc
	 */
	protected function tryImport($importPath, $parentBlock, $out) {
		$id = array();
		if($importPath[0] == "string" && isset($importPath[2]) && isset($importPath[2][0]) && preg_match('/^\[\[~(\d+)\]\]$/', $importPath[2][0], $id)) {

			if($this->content == null) {
				$this->content = new cfContent(clearFusionCMS::getDb(), clearFusionCMS::getSite());
			}

			// Load the content
			$ctnt = $this->content->getNodeData($id[1], array('content', 'lastupdated'));
			if($ctnt) {
				$this->allParsedFiles[$id[0]] = strtotime($ctnt['lastupdated']);
				$parser = $this->makeParser($id[0]);
				$root = $parser->parse($ctnt['content']);

				// set the parents of all the block props
				foreach ($root->props as $prop) {
					if ($prop[0] == "block") {
						$prop[1]->parent = $parentBlock;
					}
				}

				// copy mixins into scope, set their parents
				// bring blocks from import into current block
				// TODO: need to mark the source parser	these came from this file
				foreach ($root->children as $childName => $child) {
					if (isset($parentBlock->children[$childName])) {
						$parentBlock->children[$childName] = array_merge(
							$parentBlock->children[$childName],
							$child);
					} else {
						$parentBlock->children[$childName] = $child;
					}
				}

				list($top, $bottom) = $this->sortProps($root->props, true);
				$this->compileImportedProps($top, $parentBlock, $out, $parser, FLAPPPATH . 'lessphp/mixins/');

				return array(true, $bottom, $parser, FLAPPPATH . 'lessphp/mixins/');
			}
			else {
				return array(false, null);
			}
		}
		else
			return parent::tryImport($importPath, $parentBlock, $out);
	}
}