<?php

/**
 * Class Dalten_Export_Api_Bazos Export na Bazoš.
 */
class Dalten_Export_Api_Bazos implements Dalten_Export_Api_ApiInterface, Dalten_Export_Api_LoggableApiInterface, Dalten_Export_Api_TopListingInterface
{
    /**
     * @var Dalten_Export_Bazos
     */
    private $_export;
    /**
     * @var Serenity_Config_Config
     */
    private $_config;
    /**
     * @var Dalten_Export_Api_Backend_Bazos
     */
    private $_backend;

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

    public function openConnection($login, $password, $softwareKey = '', array $additionalParams = array())
    {
        // TODO - kontrolovat jméno a heslo, asi zkusit stáhnout seznam inzerátů
        $this->_backend->prihlasit($login, $password);
        return new Dalten_Export_Api_ServerResponse(true);
    }

    protected function specialniPscDleStatu(array $listingData)
    {
        if ($listingData['nemovitost_uir_stat']=='SK') {
            $listingData['nemovitost_psc'] = 98765; // Slovensko
        } elseif ($listingData['nemovitost_uir_stat']!='CZ') {
            $listingData['nemovitost_psc'] = 98766; // zahraničí
        }

        return $listingData;
    }

    public function addListing(array $listingData, array $userData, array $images = array(), array $additionalParams = array())
    {
        $listingData = $this->specialniPscDleStatu($listingData);
        $listingData = $this->_export->convertEntityValues('listing', $listingData, $this->_config->listing);
        $userData = $this->_export->convertEntityValues('broker', $userData, $this->_config->broker);

        if (isset($additionalParams['result']['idad'])) {
            $listingData['idad'] = $additionalParams['result']['idad'];
        }

        if (empty($listingData['lokalita'])) {
            return new Dalten_Export_Api_ServerResponse(false, 500, 'Nepodařilo se dohledat PSČ nabídky.');
        }

        $responseXml = $this->_backend->pridani($listingData + $userData, $images);

        if (isset($responseXml->code) && $responseXml->code=='OK') {
            $response = new Dalten_Export_Api_ServerResponse(true, 200, 'OK');
            $response->setData(['detailUrl'=>(string) $responseXml->url, 'idad'=>(string) $responseXml->description]);
            return $response;
        } elseif (isset($responseXml->description)) {
            $response = new Dalten_Export_Api_ServerResponse(false, 500, (string) $responseXml->description);
            if (isset($additionalParams['result']['idad'])) {
                // aby se při nepovedených updatech neztrácelo idad, nastavíme ho ručně
                $response->setData(['idad'=>$additionalParams['result']['idad']]);
            }
            return $response;
        }

        return new Dalten_Export_Api_ServerResponse(false, 500, 'Nastala neočekávaná chyba.');
    }

    public function deleteListing(array $listingData, array $additionalParams = array())
    {
        if (!isset($additionalParams['result']['idad'])) {
            return new Dalten_Export_Api_ServerResponse(false, 500, 'Není možné smazat nabídku, neboť není uloženo vzdálené ID.');
        }

        $responseXml = $this->_backend->smazani($additionalParams['result']['idad']);

        if (isset($responseXml->code) && $responseXml->code=='OK') {
            return new Dalten_Export_Api_ServerResponse(true, 200, $responseXml->description);
        } elseif (isset($responseXml->description)) {
            return new Dalten_Export_Api_ServerResponse(false, 500, $responseXml->description);
        }

        return new Dalten_Export_Api_ServerResponse(false, 500, 'Nastala neočekávaná chyba.');
    }

    /**
     * Stáhne dotazy pro danou firmu z Bazoše.
     *
     * @param DateTime $from Od kdy.
     * @param DateTime $to   Do kdy.
     *
     * @return Dalten_Export_Api_ServerResponse Odpověď serveru.
     */
    public function getAnswers(DateTime $from, DateTime $to)
    {
        $answers = $this->_backend->getAnswers($from, $to);

        if (!$answers || is_null($answers)) {
            return new Dalten_Export_Api_ServerResponse(false);
        }

        if (isset($answers['error_code'])) {
            return new Dalten_Export_Api_ServerResponse(false, $answers['error_code'], $answers['message']);
        }

        return new Dalten_Export_Api_ServerResponse(true, 200, 'OK', $answers);
    }

    public function getListingsList()
    {
        throw new BadMethodCallException('Neimplementováno!');
    }

    /** {@inhertiDoc} */
    public function topListing(array $listingData, array $additionalParams = array())
    {
        if (!isset($additionalParams['result']['idad'])) {
            return new Dalten_Export_Api_ServerResponse(false, 500, 'Není nastaveno idad, nelze vytopovat.');
        }

        $responseXml = $this->_backend->topovani($additionalParams['result']['idad']);

        if (isset($responseXml->code) && $responseXml->code=='OK') {
            return new Dalten_Export_Api_ServerResponse(true, 200, $responseXml->description);
        } elseif (isset($responseXml->description)) {
            return new Dalten_Export_Api_ServerResponse(false, 500, $responseXml->description);
        }

        return new Dalten_Export_Api_ServerResponse(false, 500, 'Nastala neočekáváaná chyba.');
    }


    public function setLogger(Dalten_Export_Api_Backend_Logger_LoggerInterface $logger)
    {
        $this->_backend->setLogger($logger);
        return true;
    }

    public function removeLogger()
    {
        $this->_backend->removeLogger();
        return $this;
    }

}


