<?php
Class CSVGenerator { 
	public $filename = "";
	public $lines;
	public $separator;
	public $escape_character;
	public $newline_character;
	public $no_of_lines = 0;
	
	function __construct($filename = "", $separator = ",", $escape_character = "", $newline_character = "\n") {
		$this->lines = array();
		$this->separator = $separator;
		$this->escape_character = $escape_character;
		$this->filename = $filename;
		$this->newline_character = $newline_character;
		
	}
	
	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(strpos($string, $this->separator) === false){
				
			} 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 = "";
		foreach($this->lines as $line){
			if(!is_null($line) && count($line) > 0){
				if($string != "") $string .= $this->newline_character;
				$string .= $this->generateLine($line);
				$this->no_of_lines += 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);
	}
} 

?>