/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.commons.messaging;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;

/**
 * Implementation of {@link SenderFactory}.
 */
class SenderFactoryImpl implements SenderFactory {
    private final ConnectionManager connectionManager;

    private final Codec codec;

    /**
     * Constructor.
     *
     * @param connectionManager
     * @param codec
     */
    public SenderFactoryImpl(ConnectionManager connectionManager,
            Codec codec) {
        this.connectionManager = connectionManager;
        this.codec = codec;
    }

    @Override
    public Sender newSender() throws MessagingException {
        return new SenderImpl(getChannel(), codec);
    }

    private Channel getChannel() throws MessagingException {
        Connection connection = connectionManager.getConnection();

        try {
            return connection.createChannel();
        } catch (IOException e) {
            throw new MessagingException("Failed to create sender.", e);
        }
    }
}
