<?php
namespace ModulesAbstract\ImportedOrdersFileManager\Model\Filters;

class DownloadAndCompressExtractedData extends DownloadAndCompress
{
	protected $fileTempName = null;

	protected $rowTemplate = [];
	protected $inputColumns = [];
	protected $injectedVirtualColumns = 0;

	/**
	 * (non-PHPdoc)
	 * @see \ModulesAbstract\ImportedOrdersFileManager\Model\Filters\AbstractFilter::validateInput()
	 */
	protected function validateInput($input)
	{
		return true;
	}

	/**
	 * (non-PHPdoc)
	 * @see \ModulesAbstract\ImportedOrdersFileManager\Model\Filters\AbstractFilter::checkFileAndUpdateAttributes()
	 */
	protected function checkFileAndUpdateAttributes($file)
	{
		$valid = true;

		if (!$this->folderTempName) {
			$folderTempName = \Engine\Dir::tempnam(sprintf("%s-%s", __CLASS__, \Engine\RandomGenerator::randomString(10)));
			if ($folderTempName === FALSE) {
				$valid = false;
			}
			$this->folderTempName = $folderTempName;


			$this->rowTemplate = [];
			$this->rowTemplate['folder'] = null;
			$this->rowTemplate['file'] = null;

			$source = $this->source;
			$inputColumns = [];
			while ($source) {
				$k = $source->getInput();
				if ($k!='all' && $source->getFilterMode()=='extract') {
					$inputColumns[]=$k;
				}

				$source = $source->getSource();
				if (!($source instanceof \ModulesAbstract\ImportedOrdersFileManager\Model\Filters\AbstractFilter)) {
					$source = null;
				}
			}

			$inputColumns = array_reverse($inputColumns);
			foreach ($inputColumns as $k) {
				$this->rowTemplate[$k] = null;
			}

			$this->inputColumns = $inputColumns;

			if (!$this->fileTempName) {
				$this->fileTempName = new \App\Utils\CSV\Writer\UnbufferedWriter();
				$this->fileTempName->appendHeaderRow(array_keys($this->rowTemplate));
			}
		}


		$row = $this->rowTemplate;
		$row['folder'] = $file->getDirname();
		$row['file'] =	$file->getFullName();

		foreach ($this->current->getExtractedData() as $k=>$v) {
			if (!array_key_exists($this->inputColumns[$k], $row)) {
				// "extend" previous column
				$this->injectedVirtualColumns++;
				$newColumn = "(virtual #{$this->injectedVirtualColumns})";

				$this->rowTemplate[$newColumn] = null;
				$this->inputColumns[$k] = $newColumn;
				$row[$newColumn] = null;

				$this->fileTempName->resetHeader()->appendHeaderRow(array_keys($this->rowTemplate));
			}
			$row[$this->inputColumns[$k]] = $v;
		}

		$this->fileTempName->appendRow($row);

		$valid = true;
		return $valid;
	}

	public function createArchive()
	{
		$this->fileTempName->save($this->folderTempName."{$this->proposeDownloadFilename()}.csv");
		return parent::createArchive();
	}

	public function proposeDownloadFilename()
	{
		$ret = [];
		foreach ($this->inputColumns as $k) {
			$str = $k;
			$str = preg_replace("/(\\\$data|\\\$transaction)/", '', $str);
			$str = preg_replace("/[^a-zA-Z0-9_,.]/", '_', $str);
			$str = preg_replace("/[_]+/", '_', $str);
			$str = trim($str, '_');
			$ret[]= $str;
		}
		$fname = implode(",", $ret);
		$fname = preg_replace("/virtual_([0-9]+)/", '#$1', $fname);

		$maxLen = 100;
		return (strlen($fname)>($maxLen+3)?substr($fname, 0, $maxLen).'...':$fname);
	}
}
