<?php
Class CSVGenerator { 
	public $filename = "";
	public $lines;
	public $separator;
	public $escape_character;
	public $newline_character;
	public $no_of_lines = 0;
	public $forceQuote = false;
	function __construct($filename = "", $separator = ",", $escape_character = "", $newline_character = "\n", $forceQuote = false) {
		$this->lines = array();
		$this->separator = $separator;
		$this->escape_character = $escape_character;
		$this->filename = $filename;
		$this->newline_character = $newline_character;
		$this->forceQuote = $forceQuote;
	}
	
	public function addLine($line, $pos = ""){
		if($pos != "")
			Log::write("add : " . $pos);
		$this->lines[] = $line;
	}
	
	public function addLines($lines){
		foreach($lines as $line){
			$this->lines[] = $line;
		}
	}
	
	public function generateString($string){
		if($this->escape_character == ""){
			if(!$this->forceQuote){
				$needQuote = false;
				if(strpos($string, $this->separator) === false){
				} else {
					$needQuote = true;
				} 
				if(strpos($string, '"') === false) {
				} else {
					$needQuote = true;
					$string = str_replace('"' , '""', $string);
				}

				if($needQuote){
					$string = '"' . $string . '"';
				} 
			} else {
				$string = "\"" . $string . "\"";
			}
		} else {
			$string = str_replace($this->escape_character, $this->escape_character . $this->escape_character, $string);
			$string = str_replace($this->separator, $this->escape_character . $this->separator, $string);
		}
		return $string;
	}
	
	public function generateLine($line){
		$string = "";
		$first = true;
		foreach($line as $element){
			if(!$first) $string .= $this->separator;
			$string .= $this->generateString($element);
			$first = false;
		}
		return $string;
	}
	
	public function generateLines(){
		$string = "";
        $counter = 1;
		foreach($this->lines as $line){
			if(!is_null($line) && count($line) > 0){
				//if($string != "") $string .= $this->newline_character;
				//$string .= $this->generateLine($line);
                $temp = str_replace("[LINE_COUNTER]", $counter, $this->generateLine($line)) ;
                $string .= $temp . $this->newline_character;
				$this->no_of_lines += 1;
                $counter+=1;
			}
		}
		return $string;
	}
	
	public function output(){
		$this->no_of_lines = 0;
		$string = $this->generateLines();
		
		$string = str_replace("[NO_OF_LINES]", $this->no_of_lines, $string);
		
		file_put_contents($this->filename, $string);
	}
} 

?>