package org.mercury_im.messenger.xmpp;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.stringprep.XmppStringprepException;
import org.mercury_im.messenger.entity.Account;

public class XmppConnectionFactory {

    private static final int DEFAULT_PORT = 5222;
    private static final int CONNECTION_TIMEOUT = 30 * 1000;

    public AbstractXMPPConnection createConnection(Account account) {
        try {
            return new XMPPTCPConnection(XMPPTCPConnectionConfiguration.builder()
                    .setConnectTimeout(CONNECTION_TIMEOUT)
                    .setXmppAddressAndPassword(account.getAddress(), account.getPassword())
                    .setHost(determineHost(account))
                    .setPort(determinePort(account))
                    .build());
        } catch (XmppStringprepException e) {
            throw new AssertionError("Account has invalid address: " + account.getAddress(), e);
        }
    }

    private String determineHost(Account account) throws XmppStringprepException {
        return account.getHost() != null ? account.getHost() : JidCreate.domainBareFrom(account.getAddress()).toString();
    }

    private int determinePort(Account account) {
        return account.getPort() != 0 ? account.getPort() : DEFAULT_PORT;
    }
}
