<?php
/**
 * Export na Toplak.hu
 *
 * @category   Dalten
 * @package    Export
 * @subpackage Api
 */
class Dalten_Export_Api_Backend_Toplakhu implements Dalten_Export_Api_Backend_LoggableBackendInterface
{
	const XML_SKELETON = '<?xml version="1.0" encoding="utf-8"?><RespoAds/>';
	private $_logger = null;
	private $_ftp = null;
	private $_xml = null;
	private $_userId = 0;
	private $_fileName = null;
	private $_zip = null;
	private $_closeCounter = 0;

	public function addAd(array $uzivatel, array $ad, array $pictures)
	{
		/** @var $thisAd Dalten_Xml_SimpleXml */
		$thisAd = $this->_xml->addChild('RespoAd');

		$thisAd->addChild('User')->addChild('userid', $this->_userId);
		$contactS = $thisAd->addChild('Contact');
		$adSection = $thisAd->addChild('Ad');

		$contactS->addChild('public', 1);
		$contactS->addChild('externaalid', $uzivatel['id']);
		$contactS->addChild('firstname', $uzivatel['uzivatel_os_jmeno']);
		$contactS->addChild('lastname', $uzivatel['uzivatel_os_prijmeni']);
		$contactS->addChild('telephone', $uzivatel['telefon']);
		$contactS->addChild('email', $uzivatel['email']);
		$contactS->addChild('active', 1);
		$contactS->addChild('refcountryid', 96); //konstanta


		$adSection->addChild('refuserid', $this->_userId);

		foreach ($ad as $ak => $av) {
			$adSection->addChild($ak, $av);
		}

		$picturesNode = $thisAd->addChild('Pictures');
		$this->zipAdPictures($pictures, $picturesNode);
	}

	function zipAdPictures($pictures, Dalten_Xml_SimpleXml $picturesNode) {
		/** @var $zip ZipArchive */
		$zip = $this->_zip;
		foreach ($pictures as $image) {
			$tmp = explode('/', $image['soubor']);
			$tmp = array_pop($tmp);

			if (file_exists($image['soubor'])) {

				$obrazekOK = $zip->addFile($image['soubor'], $tmp);
				if ($obrazekOK) {
					$currPictureNode = $picturesNode->addChild('picture');
					$currPictureNode->addAttribute('originalname', $tmp);
					$currPictureNode->addAttribute('refexternaltype', '3');
				}
			}
		}
	}

	function setFtpInstance(Dalten_Ftp_Connector $ftp) {
		$this->_ftp = $ftp;
		if ($this->_logger) {
			$ftp->setLogger($this->_logger);
		}
	}

	function open($userId) {
		$this->_xml = new Dalten_Xml_SimpleXml(self::XML_SKELETON);
		$this->_userId = $userId;
		$this->_fileName = tempnam(sys_get_temp_dir(),'zip');
		$zip = new ZipArchive();
		$zip->open( $this->_fileName , ZipArchive::CREATE);
		$this->_zip = $zip;
		return $this;
	}

	function closeAndSend() {
		/** @var $ftp Dalten_Ftp_Connector */
		$ftp = $this->_ftp;

		/** @var $zip ZipArchive */
		$zip = $this->_zip;

		/** @var $xml Dalten_Xml_SimpleXml */
		$xml = $this->_xml;
		$xmlText = $xml->asXML();

		if (!$zip->addFromString('info.xml', $xmlText)) {
			echo 'NEPOVEDLO SE HNISE' . PHP_EOL;
		}
		if (!$zip->close()) {
			echo 'NEPOVEDL SE ZIP' . PHP_EOL;
		}

		$this->_zip = null;

		$ftp->put( $this->_fileName, date('Ymd-His') . '-' . $this->_closeCounter . '.zip', FTP_BINARY);
		$this->_closeCounter++;
	}

	/**
	 * Zjisti co se zipu stalo (pro debug)
	 *
	 * @param int $status status ze ZipArchivu
	 *
	 * @return string Chybová hláška
	 */
	function ZipStatusString($status)
	{
		switch ((int) $status) {
			case ZipArchive::ER_OK:
				return 'N No error';
			case ZipArchive::ER_MULTIDISK:
				return 'N Multi-disk zip archives not supported';
			case ZipArchive::ER_RENAME:
				return 'S Renaming temporary file failed';
			case ZipArchive::ER_CLOSE:
				return 'S Closing zip archive failed';
			case ZipArchive::ER_SEEK:
				return 'S Seek error';
			case ZipArchive::ER_READ:
				return 'S Read error';
			case ZipArchive::ER_WRITE:
				return 'S Write error';
			case ZipArchive::ER_CRC:
				return 'N CRC error';
			case ZipArchive::ER_ZIPCLOSED:
				return 'N Containing zip archive was closed';
			case ZipArchive::ER_NOENT:
				return 'N No such file';
			case ZipArchive::ER_EXISTS:
				return 'N File already exists';
			case ZipArchive::ER_OPEN:
				return 'S Can\'t open file';
			case ZipArchive::ER_TMPOPEN:
				return 'S Failure to create temporary file';
			case ZipArchive::ER_ZLIB:
				return 'Z Zlib error';
			case ZipArchive::ER_MEMORY:
				return 'N Malloc failure';
			case ZipArchive::ER_CHANGED:
				return 'N Entry has been changed';
			case ZipArchive::ER_COMPNOTSUPP:
				return 'N Compression method not supported';
			case ZipArchive::ER_EOF:
				return 'N Premature EOF';
			case ZipArchive::ER_INVAL:
				return 'N Invalid argument';
			case ZipArchive::ER_NOZIP:
				return 'N Not a zip archive';
			case ZipArchive::ER_INTERNAL:
				return 'N Internal error';
			case ZipArchive::ER_INCONS:
				return 'N Zip archive inconsistent';
			case ZipArchive::ER_REMOVE:
				return 'S Can\'t remove file';
			case ZipArchive::ER_DELETED:
				return 'N Entry has been deleted';
			default:
				return sprintf('Unknown status %s', $status);
		}
	}

	/**
	 * @param Dalten_Export_Api_Backend_Logger_LoggerInterface $logger instance loggeru
	 *
	 * @return Dalten_Export_Api_Backend_Toplakhu fluent inteface
	 */
	public function setLogger(Dalten_Export_Api_Backend_Logger_LoggerInterface $logger)
	{
		$this->_logger = $logger;
		if ($this->_ftp instanceof Dalten_Export_Api_Backend_LoggableBackendInterface) {
			$this->_ftp->setLogger($logger);
		}
		return $this;
	}

	/**
	 * Odstraní nastavený logger pro backend.
	 *
	 * @return Dalten_Export_Api_Backend_Sreality Fluent interface.
	 */
	public function removeLogger()
	{
		$this->_logger = null;
		if ($this->_ftp instanceof Dalten_Export_Api_Backend_LoggableBackendInterface) {
			$this->_ftp->removeLogger();
		}
		return $this;
	}
}
