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

class DownloadAndCompress extends AbstractFilter
{
	/**
	 * Stores the temporary folder name where the archive will be compressed
	 * @var String
	 */
	protected $folderTempName = NULL;

	/**
	 * (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;
		}

		// put files in folder
		if (!\Engine\File::create($this->folderTempName.$file->getFullName(), $file->getContent())) {
			$valid = false;
		}

		return $valid;
	}

	public function createArchive()
	{
		$zip = new \App\Archive\Compress\Zip();
		$fileName = \Engine\File::tempnam(sprintf("%s-%s.zip", __CLASS__, \Engine\RandomGenerator::randomString(10)));

		$zip
			->open($this->folderTempName)
			->setCompressionLevel(\App\Archive\Compress\Zip::COMPRESS_HIGH)
			->compressTo($fileName)
			->close();

		// remove folder
		\Engine\Dir::delete($this->folderTempName);

		return $fileName;
	}
}