<?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);
	}

	/**
	 * Generate CSV content as string in memory
	 */
	public function saveAsStr()
	{
		$memoryStream = fopen('php://temp', 'r+');

		foreach ($this->headerRows as $row) {
			$this->fputcsv($memoryStream, $row, $this->options['delimiter'], $this->options['enclosure'], $this->options['escape_char']);
		}

		foreach ($this->rows as $row) {
			$this->fputcsv($memoryStream, $row, $this->options['delimiter'], $this->options['enclosure'], $this->options['escape_char']);
		}

		rewind($memoryStream);
		$content = stream_get_contents($memoryStream);
		fclose($memoryStream);

		return $content;
	}
}
