package org.mercury_im.messenger.core.connection;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.packet.id.StanzaIdSource;
import org.jivesoftware.smack.packet.id.StanzaIdSourceFactory;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jxmpp.stringprep.XmppStringprepException;
import org.mercury_im.messenger.entity.Account;

import javax.inject.Inject;

public class XmppTcpConnectionFactory implements XmppConnectionFactory {

    private static final int CONNECTION_TIMEOUT = 30 * 1000;

    private final StanzaIdSourceFactory stanzaIdSourceFactory;

    @Inject
    public XmppTcpConnectionFactory(StanzaIdSourceFactory stanzaIdSourceFactory) {
        this.stanzaIdSourceFactory = stanzaIdSourceFactory;
    }

    public AbstractXMPPConnection createConnection(Account account) {
        try {
            XMPPTCPConnectionConfiguration.Builder configBuilder =
                    XMPPTCPConnectionConfiguration.builder()
                            .setStanzaIdSourceFactory(stanzaIdSourceFactory)
                            .setConnectTimeout(CONNECTION_TIMEOUT)
                            .setXmppAddressAndPassword(account.getAddress(), account.getPassword());
            if (account.getHost() != null) {
                configBuilder.setHost(account.getHost());
            }
            if (account.getPort() != 0) {
                configBuilder.setPort(account.getPort());
            }
            return new XMPPTCPConnection(configBuilder.build());
        } catch (XmppStringprepException e) {
            throw new AssertionError("Account has invalid address: " + account.getAddress(), e);
        }
    }
}
