<?php

	require("lib/CSS-Compressor.php");
	require("lib/JS-Compressor.php");

	class FrontMinify{
		
		const OFF = false;
		const ON = true;
		const off = false;
		const on = true;
		const JS = 2;
		const CSS = 3;

		public $debug = false;

		private $timeStart = null;
		private $toCompress = array();
		private $typeFiles = array();
		private $CSSmin;
		private $JSmin;

		function __construct(){
			$this->CSSmin = new CSSmin;
			$this->JSmin = new Minifier;
		}

		public function addFile($input, $output){

			if($this->debug == true && $this->timeStart == null)
				$this->timeStart = microtime(TRUE);

			$final = null;
			if(is_array($input)){
				foreach ($input as $files) {
					$file = file_get_contents($files);
					$final .= "\n" . $file;
				}
			}else{
				$file = file_get_contents($input);
				$final .= "\n" . $file;
			}
			$this->toCompress[$output] = $final;
			$this->typeFiles[] = (strpos($output, '.js') != false) ? FrontMinify::JS : FrontMinify::CSS;
		}

		public function execute($sw = null){
			if($sw == null)
				$sw = FrontMinify::ON;

			if($sw == true){
				$i = 0;
				foreach($this->toCompress as $output => $plainText){
					preg_match_all('/\/\*.+?\*\//s', $plainText, $newPlainText);
					for($x = 0; $x < count($newPlainText[0]); $x++){
						$plainText = str_replace($newPlainText[0][$x], '', $plainText);
					}
					if($this->typeFiles[$i] == FrontMinify::CSS){
						$finalFile = $this->CSSmin->run($plainText);
					}else{
						$finalFile = $this->JSmin->minify($plainText);
					}
					$handler = fopen($output, 'w');
					fwrite($handler, $finalFile);
					fclose($handler);
					$i++;
				}
			}

			if($this->debug == true)
				print_r("Elapsed time: " . number_format((microtime(TRUE) - $this->timeStart), 6). 's');

		}

	}