<?php
namespace App\Utils\CSV\Writer;

/**
 * Write data into CSV file. Stores all rows in memory, until the save() call is made
 * @author oana.stan
 */
class BufferedWriter extends Writer
{
	protected $headerRows = [];
	protected $rows = [];

	/**
	 * Write into file all rows
	 */
	public function fromArray($rows)
	{
		$this->rows = $rows;
		return $this;
	}

	/**
	 * Write row by row into file
	 */
	public function appendRow($row)
	{
		$this->rows[] = $row;
		return $this;
	}

	/**
	 * Append a row in the header
	 */
	public function appendHeaderRow($row)
	{
		$this->headerRows[] = $row;
		return $this;
	}

	/**
	 * Reset the internal header structure
	 */
	public function resetHeader()
	{
		$this->headerRows = [];
		return $this;
	}

	/**
	 * Save file
	 */
	public function save($file)
	{
		// open file for write
		$fp = fopen($file, "w");

		// write into file
		foreach ($this->headerRows as $row) {
			$this->fputcsv($fp, $row, $this->options['delimiter'], $this->options['enclosure'], $this->options['escape_char']);
		}

		// write into file
		foreach ($this->rows as $row) {
			$this->fputcsv($fp, $row, $this->options['delimiter'], $this->options['enclosure'], $this->options['escape_char']);
		}


		// close file
		fclose($fp);
	}
}
