<?php
require_once __DIR__ . '/../../../vendor/autoload.php';
require_once 'Zend/Loader/Autoloader.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

$loader = Zend_Loader_Autoloader::getInstance();

class Agro_RabbitMQ_RpcClientBase
{
    protected $connection;
    protected $channel;
    protected $config;
    protected $nomeFila;

    public function __construct(string $env)
    {
        $this->config = new Zend_Config_Ini( __DIR__ . '/../../../application/config/application.ini', $env);
        try {
            $this->connection = new AMQPStreamConnection(
                $this->config->rabbitmq->params->host,
                $this->config->rabbitmq->params->port,
                $this->config->rabbitmq->params->username,
                $this->config->rabbitmq->params->password
            );
            $this->channel = $this->connection->channel();

            if (empty($this->channel)) {
                throw new Exception("Não foi possível criar uma canal de conexão com os parâmetros informados.");
            }
        } catch (Exception $e) {
            throw new Exception('Erro ao conectar com servidor RabbitMQ: ' .$e->getMessage());
        }
    }

    protected function run($payload)
    {
        try {
            if (empty($this->channel)) {
                throw new Exception("Não foi possível criar uma canal de conexão com os parâmetros informados.");
            }

            $this->channel->queue_declare(
                $this->nomeFila,
                false,
                true,
                false,
                false
            );

            $msg = new AMQPMessage(
                $payload,
                ['delivery_mode' => 2]
            );

            $this->channel->basic_publish(
                $msg,
                '',
                $this->nomeFila
            );

            $this->channel->close();
            $this->connection->close();

        } catch (Exception $e) {
            throw new Exception('Erro ao consumir servidor: ' .$e->getMessage());
        }
    }
}
