<?php
class Dalten_Export_Api_RealitniProstor extends Dalten_Export_Api_Website
{
    private Serenity_Config_Config $_config;
    private Dalten_Export_Website $_export;

    public function __construct(Dalten_Export_Website                     $export, Serenity_Config_Config $config,
                                Dalten_Export_Api_Backend_RealitniProstor $backend)
	{
		$this->_export = $export;
		$this->_config = $config;
		$this->_backend = $backend;
	}

	protected function _comparePhotos(array $listingImages, array $remoteImages)
	{
		if (count($listingImages) != count($remoteImages)) {
			return false;
		}

		$listingImages = array_values($listingImages);

		$indexedListingImages = array();
		foreach ($listingImages as $listingImage) {
			if (isset($listingImage['poradi'])) {
				$indexedListingImages[$listingImage['poradi']] = $listingImage;
			} else {
				// pokud někde chybí pořadí, nebudeme podle něj řadit :)
				$indexedListingImages = $listingImage;
				break;
			}
		}
		ksort($indexedListingImages);

		$listingImages = array_values($indexedListingImages);
		$remoteImages = array_values($remoteImages);

		foreach ($listingImages as $index => $image) {
			if (empty($remoteImages[$index])) {
				return false;
			}
			if ($image['id'] != $remoteImages[$index]['id']) {
				return false;
			}
		}

		return true;
	}

	public function _syncPhotos($id_nabidka, array $images)
	{
		$remotePhotosResponse = $this->_backend->listPhoto($this->_sessionId, $id_nabidka);
		if ($remotePhotosResponse['status']!=200) {
			return new Dalten_Export_Api_ServerResponse(false, 500, 'Nelze synchronizovat fotografie.');
		}
		if ($remotePhotosResponse['output'] instanceof Dalten_Data_ArrayObject) {
			$remotePhotos = $remotePhotosResponse['output']->toArray(true);
		} else {
			$remotePhotos = array();
		}
		$samePhotos = $this->_comparePhotos($images, $remotePhotos);
		if ($samePhotos) {
			return new Dalten_Export_Api_ServerResponse(true);
		} else {
			foreach ($remotePhotos as $image) {
				$deleteResponse = $this->_backend->delPhoto($this->_sessionId, $image['photo_id']);
				if ($deleteResponse['status']!=200) {
					return new Dalten_Export_Api_ServerResponse(false, 500, 'Nepodařilo se smazat fotografii.');
				}
			}
			foreach ($images as $image) {
				if (!file_exists($image['soubor'])) {
					continue;
				}
				$fileContent = file_get_contents($image['soubor']);
				$addResponse = $this->_backend->addPhoto(
					$this->_sessionId,
					(int) $id_nabidka,
					array(
						'photo_id'=>(string) $image['id'],
						'poradi'=>(int) $image['poradi'],
						'popis'=>(string) $image['popis'],
						'data'=> $fileContent
					)
				);
				if ($addResponse['status']!=200) {
					return new Dalten_Export_Api_ServerResponse(false, 500, sprintf('Nepodařilo se nahrát fotografii č. %d.', $image['poradi']));
				}
			}
		}
		return new Dalten_Export_Api_ServerResponse(true, 200, 'Export fotografií proběhl v pořádku.');
	}

	public function addListing(array $listingData, array $userData, array $images = array(), array $additionalParams = array())
	{
		$toUnset = array(
			'nemovitost_cena_datum_snizeni',
			'id_firma',
			'nemovitost_makler_poznamka',
			'zakazka_datum_editace',
			'zakazka_datum_vlozeno',
			'zakazka_makler',
			'old_id'
		);

		if (!$listingData['nabidka_gps_presnost']==1) {
			$toUnset[] = 'nemovitost_uir_cp';
			$toUnset[] = 'nemovitost_uir_co';
		}

		foreach ($toUnset as $name) {
			if (isset($listingData[$name])) {
				unset($listingData[$name]);
			}
		}

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

		if (
		isset($listingData['nemovitost_energeticky_stitek_priloha'])
		) {
			$priloha = realpath($listingData['nemovitost_energeticky_stitek_priloha']);
			//nemáme soubor se štítkem (realpath nechá projít prázdnou hodnotu)
			if (empty($listingData['nemovitost_energeticky_stitek_priloha']) || $priloha===false) {
				unset($listingData['nemovitost_energeticky_stitek_priloha']);
			} else {
				$listingData['nemovitost_energeticky_stitek_priloha'] = file_get_contents($listingData['nemovitost_energeticky_stitek_priloha']);
			}
		}

		$response = $this->_backend->addNabidka($this->_sessionId, $listingData);

		if (!isset($response['status'], $response['statusMessage'])) {
			return new Dalten_Export_Api_ServerResponse(false, 500, 'Bad response.');
		}

		$status = intval($response['status']);

		if ($status >= 200 && $status < 300 && $userData) {

			$photoResponse = $this->_syncPhotos($listingData['id'], $images);

			if (!$photoResponse->wasSuccessful()) {
				return $photoResponse;
			}

			$userResponse = $this->addUser($userData);

			// Pokud je export úspěšný, tak tam server rve co se nedalo do db... což nemusí uživatelé vidět
			$response['statusMessage'] = '';

			if (!$userResponse->wasSuccessful()) {
				return $userResponse;
			}
		}

		return $this->_convertDataObjectIntoServerResponse($response);
	}

	public function addUser(array $userData)
	{
		if (isset($userData['exportovat_foto']) && !$userData['exportovat_foto']) {
			unset($userData['foto']);
		}
		if (!empty($userData['foto'])) {
			$photo = realpath($userData['foto']);
			if (file_exists($photo)) {
				$photo = file_get_contents($photo);
				xmlrpc_set_type($photo, 'base64');
				$userData['foto'] = $photo;
			} else {
				unset($userData['foto']);
			}
		}
		return parent::addUser($userData);
	}


}