<?php
class Dalten_Export_Api_ViarealityAccounts
{
	/**
	 * Konvertor hodnot.
	 *
	 * @var Dalten_Export_Sreality
	 */
	private $_export;

	/**
	 * Nastavení.
	 *
	 * @var Serenity_Config_Config
	 */
	private $_config;

	/**
	 * Backend.
	 *
	 * @var Dalten_Export_Api_Backend_ViarealityAccounts
	 */
	protected $_backend;

	/**
	 * Fixní část variabilní části session ID.
	 *
	 * @var string|null
	 */
	private $_hashKey = null;

	/**
	 * Poslední platné session ID.
	 *
	 * @var string|null
	 */
	private $_sessionId = null;

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

	/**
	 * Naváže spojení se vzdáleným serverem.
	 *
	 * @param string $login            Přihlašovací jméno.
	 * @param string $password         Heslo.
	 * @param string $softwareKey      Softwarový klíč.
	 * @param array  $additionalParams Pole dalších parametrů.
	 *
	 * @return Dalten_Export_Api_ServerResponse Odpověď serveru.
	 */
	public function openConnection($login, $password, $softwareKey = '', array $additionalParams = array())
	{
		$hash = $this->_backend->getHash($login);

		if (!isset($hash->status) || $hash->status != 200) {
			return new Dalten_Export_Api_ServerResponse(
				false,
				isset($hash->status) ? $hash->status : 500,
				isset($hash->statusMessage) ? $hash->statusMessage : 'getHash failed.'
			);
		}

		$this->_sessionId = $hash->output->sessionId;
		$this->_hashKey = md5((string) $password) . (string) $softwareKey;

		$response = $this->_backend->login($this->_getSessionId(false));

		return new Dalten_Export_Api_ServerResponse(
			isset($response->status) && $response->status == 200,
			isset($response->status) ? $response->status : 500,
			isset($response->statusMessage) ? $response->statusMessage : 'No response from server'
		);
	}

	/**
	 * Vypočítá nové session ID, které posléze vrátí.
	 *
	 * @return string Nové session ID.
	 */
	protected function _getSessionId()
	{
		$fixedPart = substr($this->_sessionId, 0, 48);
		$varPart = md5($this->_sessionId . $this->_hashKey);
		$this->_sessionId = $fixedPart . $varPart;
		return $this->_sessionId;
	}

	/**
	 * Pošle informace o kanceláři.
	 *
	 * @param array $officeData Informace o kanceláři.
	 *
	 * @return Dalten_Export_Api_ServerResponse Odpověď serveru.
	 */
	public function addOffice(array $officeData)
	{
		$officeData = $this->_export->convertEntityValues('office', $officeData, $this->_config->office);
		$response = $this->_backend->addAccount($this->_getSessionId(), $officeData);
		return new Dalten_Export_Api_ServerResponse(
			$response['status']==200,
			$response['status'],
			$response['statusMessage'],
			$response['output']
		);
	}


	public function addLogo($accountId, $logoFilename)
	{
		$logo = file_get_contents($logoFilename);
		if (!$logo) {
			return new Dalten_Export_Api_ServerResponse(false, 501, 'Nepodařilo se načíst logo.');
		}
		$logo = $this->_adjustToSquare($logo);
		if ($logo===false) {
			return new Dalten_Export_Api_ServerResponse(false, 501, 'Nepodařilo se zmenšit logo.');
		}
		$response = $this->_backend->addLogo($this->_getSessionId(), $accountId, $logo);
		return new Dalten_Export_Api_ServerResponse(
			$response['status']==200,
			$response['status'],
			$response['statusMessage'],
			$response['output']
		);
	}


	public function deleteOffice(array $officeData)
	{
		$this->_backend->delAccount($this->_getSessionId(), $officeData['account_id']);
	}

	public function listOffices()
	{
		$response = $this->_backend->listAccount($this->_getSessionId());
		return new Dalten_Export_Api_ServerResponse(
			$response['status']==200,
			$response['status'],
			$response['statusMessage'],
			$response['output']
		);
	}

	public function closeConnection()
	{
		$this->_backend->logout($this->_getSessionId());
	}

	protected function _adjustToSquare($logo)
	{
		$input = imagecreatefromstring($logo);
		if (is_resource($input)) {
			$w = imagesx($input);
			$h = imagesy($input);
			ob_start();
			$success = imagejpeg($input);
			$result = ob_get_clean();
			if ($w!=$h) {
				if ($w>$h) {
					$output = imagecreatetruecolor($w, $w);
					$white = imagecolorallocate($output, 255, 255, 255);
					imagefill($output, 0, 0, $white);
					imagecopy($output, $input, 0, ($w-$h)/2, 0, 0, $w, $h);
					ob_start();
					$success = imagejpeg($output);
					$result = ob_get_clean();
					imagedestroy($output);
				} else {
					$output = imagecreatetruecolor($h, $h);
					$white = imagecolorallocate($output, 255, 255, 255);
					imagefill($output, 0, 0, $white);
					imagecopy($output, $input, ($h-$w)/2, 0, 0, 0, $w, $h);
					ob_start();
					$success = imagejpeg($output);
					$result = ob_get_clean();
					imagedestroy($output);
				}
			}
			imagedestroy($input);
			if ($success) {
				return $result;
			}
		}
		return false;
	}
}