<?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 fusionLib
 * @copyright Copyright (c) 2011 - 2013 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flBufferCss Class
 *
 * Collect CSS together, both files and inline, merging inline where possible.
 *
 * @package fusionLib
 */
class flBufferCss {
	/**
	 * Array of CSS.
	 *
	 * @var array
	 */
	private $css = array();

	/**
	 * Flags if the last added was a file
	 *
	 * @var bool
	 */
	private $lastFile = true;

	/**
	 * The last media type.
	 *
	 * @var string
	 */
	private $lastMedia = 'all';

	/**
	 * List of files to ignore.
	 *
	 * @var array
	 */
	private $ignore = array();

	/**
	 * List of files loaded.
	 *
	 * @var array
	 */
	private $files = array();

	/**
	 * Wrap the CSS in style tags.
	 */
	private function wrapLast() {
		$this->css[count($this->css) - 1] = "<style type=\"text/css\" media=\"$this->lastMedia\">\n<!--\n" . $this->css[count($this->css) - 1] . "-->\n</style>";
	}

	/**
	 * Clear the buffer.
	 */
	function clear() {
		$this->css = array();
		$this->lastFile = true;
		$this->lastMedia = 'all';
		$this->ignore = array();
		$this->files = array();
	}

	/**
	 * Set the list of files to ignore.
	 *
	 * @param array $ignore The list of files to ignore.
	 */
	function setIgnoreList($ignore) {
		$this->ignore = $ignore;
	}

	/**
	 * Get the list of files loaded.
	 *
	 * @return array The file list.
	 */
	function getFileList() {
		return $this->files;
	}

	/**
	 * Buffer inline CSS or a file.
	 *
	 * @param string $css The CSS to buffer.
	 * @param string $media The type of media to support with the CSS or null to use the last
	 * @return flBufferCss This object
	 */
	function buffer($css, $media = 'all') {

		// If file given
		if(preg_match('/\.css(\?.*)?$/', $css)) {

			// If last as inline then close it
			if(!$this->lastFile)
				$this->wrapLast();
			$this->lastFile = true;

			if(!isset($this->ignore[$css]) && !isset($this->files[$css])) {
				$this->css[] = "<link href=\"$css\" rel=\"stylesheet\" type=\"text/css\" media=\"$this->lastMedia\" />";
				$this->files[$css] = 1;
			}
		}
		// Else inline script
		else {
			// If last was a file start new
			if($this->lastFile)
				$this->css[] = "$css\n";
			else if($this->lastMedia !== $media) {
				$this->wrapLast();
				$this->css[] = "$css\n";
			}
			else
				$this->css[count($this->css) - 1] .= "$css\n";

			$this->lastFile = false;
			$this->lastMedia = $media;
		}
		return $this;
	}

	/**
	 * Get the contents of the buffer.
	 *
	 * @return string The buffer contents.
	 */
	function getBuffer() {
		if(!$this->lastFile)
			$this->wrapLast();
		$this->lastFile = true;
		return count($this->css) ? join("\n", $this->css) . "\n" : '';
	}
}
