<?php
class Dalten_Export_Api_Backend_Bazos implements Dalten_Export_Api_Backend_LoggableBackendInterface
{
    protected $_jmeno = '';
    protected $_heslo = '';
    /**
     * @var Dalten_Http_ClientInterface
     */
    private $httpClient;

    public function __construct(Dalten_Http_Client $httpClient)
    {
        $this->httpClient = $httpClient;
    }

    public function prihlasit($jmeno, $heslo)
    {
        $this->_jmeno = $jmeno;
        $this->_heslo = $heslo;
        // TODO - v budoucnu možná chceme jméno a heslo kontrolovat, asi přes výpis nabídek
    }

    public function pridani($data, $obrazky)
    {
        $data['idcomp'] = $this->_jmeno; // ID RK
        $data['heslo'] = $this->_heslo;

        $obrazky = array_slice($obrazky, 0, 10);
        $poslaneSoubory = [];
        foreach ($obrazky as $ord=>$obrazek) {
            $poslaneSoubory['souborp' . ($ord > 0 ? $ord+1 : '')] = $obrazek['soubor'];
        }

        $responseXml = $this->httpClient->post('http://reality.bazos.cz/insertport.php', $data, $poslaneSoubory);

        return simplexml_load_string($responseXml);
    }

    public function smazani($id)
    {
        $responseXml = $this->httpClient->post('https://reality.bazos.cz/topdelport.php', [
            'idcomp'=> $this->_jmeno,
            'heslo' => $this->_heslo,
            'idad' => $id,
            'operace' => 'smazat'
        ]);

        return simplexml_load_string($responseXml);
    }

    public function topovani($id)
    {
        $responseXml = $this->httpClient->post('https://reality.bazos.cz/topdelport.php', [
            'idcomp'=> $this->_jmeno,
            'heslo' => $this->_heslo,
            'idad' => $id,
            'operace' => 'topovat'
        ]);

        return simplexml_load_string($responseXml);
    }

    public function getAnswers(DateTime $from, DateTime $to)
    {
        $responseJson = $this->httpClient->get(
            sprintf(
                'https://rk.bazos.cz/answers.php?idcomp=%s&password=%s&limit=1000&offset=0&date_from=%d&date_to=%',
                $this->_jmeno,
                $this->_heslo,
                $from->format('U'),
                $to->format('U')
            )
        );

        return json_decode($responseJson, true);
    }

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

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


}
