<?php
/**
 * Backend pro export na Realsoft.sk. Veškerá logika je zde.
 *
 * @category   Dalten
 * @package    Export
 * @subpackage Api
 */
class Dalten_Export_Api_Backend_RealsoftSk implements Dalten_Export_Api_Backend_LoggableBackendInterface
{
	/** @var  Dalten_Http_ClientInterface */
	protected $_httpClient;

	/** @var  Dalten_Export_RealsoftSk */
	protected $_export;

	/** @var  Serenity_Config_Config */
	protected $_config;

	/** @var  Dalten_AddressConverter_RealsoftSk_Interface */
	protected $_addressConverter;
	protected $_newAddressConverter;

	protected $_importURL = 'http://realsoft.dalten.com/api/import/';

	protected $_user = '';
	protected $_pass = '';

	/** @var  Dalten_Export_Api_Backend_Logger_LoggerInterface */
	protected $_logger;

	/**
	 * Konstruktor.
	 *
	 * @param Dalten_Export_RealsoftSk                     $export           Export (převodník).
	 * @param Serenity_Config_Config                       $config           Konfigurák exportu.
	 * @param Dalten_Http_ClientInterface                  $http             HTTP klient.
	 * @param Dalten_AddressConverter_RealsoftSk_Interface $addressConverter Převodník adres.
	 */
	public function __construct(
		Dalten_Export_RealsoftSk $export,
		Serenity_Config_Config $config,
		Dalten_Http_ClientInterface $http,
		Dalten_AddressConverter_RealsoftSk_Interface $addressConverter
	) {
		$this->_export = $export;
		$this->_config = $config;
		$this->_httpClient = $http;
		$this->_addressConverter = $addressConverter;

		$this->_newAddressConverter = new Dalten_AddressConverter_RealsoftSk_Realsoft();
	}

	/**
	 * Přihlásí se k serveru. Vždy uspěje.
	 *
	 * @param string $login            Jméno.
	 * @param string $password         Heslo.
	 * @param string $softwareKey      Softwarový klíč (nepoužívá se).
	 * @param array  $additionalParams Jiné parametry (nepoužívá se).
	 *
	 * @return Dalten_Export_Api_ServerResponse Odpověď serveru.
	 */
	public function openConnection($login, $password, $softwareKey = '', array $additionalParams = array())
	{
		$this->_user = $login;
		$this->_pass = $password;
		return new Dalten_Export_Api_ServerResponse(true);
	}

	/**
	 * Vyexportuje nabídku (případně makléře) na Realsoft.sk. Slouží i k mazání.
	 *
	 * @param array $listingData       Informace o nabídce ve formátu Irestu 1.
	 * @param array $userData          Informace o makléři ve formátu Irestu 1. Pokud jsou prázdné, nepošlou se.
	 * @param array $images            Informace o obrázcích ve tvaru Irestu 1.
	 * @param array $additionalParams  Další informace.
	 * @param bool  $remove            Mažeme nabídku?
	 *
	 * @return Dalten_Export_Api_ServerResponse Odpověď serveru.
	 */
	public function export(array $listingData, array $userData, array $images = array(), array $additionalParams = array(), $remove=false)
	{
		if (!empty($userData)) {
			$agent = $this->_export->convertEntityValues('agent', $userData, $this->_config->agent);

			$agentResponseJson = $this->_httpClient->post($this->_importURL, array(
				'user' => $this->_user,
				'pass' => $this->_pass,
				'action' => 'agent',
				'data' => json_encode($agent)
			));

			$agentResponse = json_decode($agentResponseJson, true);

			if (!in_array($agentResponse['code'], array(1, 2))) {
				return new Dalten_Export_Api_ServerResponse(
					false,
					$agentResponse['code'],
					$agentResponse['message']
				);
			}
		}

		$listingData['_export'] = !$remove;
		$listingData['_show_web'] = !$remove;

		if ($listingData['pouzit_realsoft_adresu']) {
		    if (!$this->_newAddressConverter->canConvertAddress($listingData)) {
		        return new Dalten_Export_Api_ServerResponse(
                    false,
                    500,
                    'Adresa nieje vyplnená podľa špecifikácie Realsoft.'
                );
            }
            $listingData = $this->_newAddressConverter->convertAddress($listingData);
        } else {
            $listingData = $this->_addressConverter->convertAddress($listingData);
        }

		if (!empty($additionalParams['listing']['hide_price'])) {
			$listingData['nemovitost_cena_prodej'] = 0;
			$listingData['nemovitost_cena_pronajem'] = 0;
			$listingData['nemovitost_cena_poznamka'] = 'Info v RK';
		}

		if (!empty($additionalParams['listing']['hide_street'])) {
			$listingData['nabidka_gps_x'] = 0;
			$listingData['nabidka_gps_y'] = 0;
			$listingData['street_show'] = 0;
		}

		if (isset($additionalParams['listing']['realsoft_blacklist'])) {
			$listingData['notexport_portals'] = implode(',', $additionalParams['listing']['realsoft_blacklist']);
		}

		$object = $this->_export->convertEntityValues('object', $listingData, $this->_config->object);

		$object['agent_id'] = $listingData['id_uzivatel'];

		$object['langData']['sk'] = array(
			'title' => $listingData['nemovitost_titulek'],
			'description' => $listingData['nemovitost_popis_detailni']
		);

		foreach ($images as $ord=>$image) {
			$object['images'][] = $image['url'];
		}

		if ($this->_logger) {
			$this->_logger->logRemoteCall('data', var_export($object, true));
		}

		$objectResponseJson = $this->_httpClient->post($this->_importURL, array(
			'user' => $this->_user,
			'pass' => $this->_pass,
			'action' => 'object',
			'data' => json_encode($object)
		));

		$objectResponse = json_decode($objectResponseJson, true);
		if (is_array($objectResponse['message'])) {
			$msg = array();
			foreach ($objectResponse['message'] as $k=>$v) {
				$msg[] = $k .': ' . $v . PHP_EOL;
			}
			$objectResponse['message'] = implode(' ' . PHP_EOL, $msg);
		}
		return new Dalten_Export_Api_ServerResponse(
			$objectResponse['code']==1 || $objectResponse['code']==2,
			$objectResponse['code'],
			$objectResponse['message']
		);
	}

	/**
	 * Nastaví logger pro backend.
	 *
	 * Logger bude použit pouze pokud to backend dovoluje.
	 *
	 * @param \Dalten_Export_Api_Backend_Logger_LoggerInterface $logger Instance loggeru.
	 *
	 * @return Dalten_Export_Api_LoggableApiInterface Fluent interface.
	 */
	public function setLogger(Dalten_Export_Api_Backend_Logger_LoggerInterface $logger)
	{
		$this->_logger = $logger;
		if ($this->_httpClient instanceof Dalten_Export_Api_Backend_LoggableBackendInterface) {
			$this->_httpClient->setLogger($logger);
		}
	}

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


}
