001/**
002 *
003 * Copyright 2017 Florian Schmaus.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smack.chat2;
018
019import org.jivesoftware.smack.Manager;
020import org.jivesoftware.smack.SmackException.NotConnectedException;
021import org.jivesoftware.smack.XMPPConnection;
022import org.jivesoftware.smack.packet.Message;
023import org.jivesoftware.smack.packet.Presence;
024
025import org.jxmpp.jid.EntityBareJid;
026import org.jxmpp.jid.EntityFullJid;
027import org.jxmpp.jid.Jid;
028
029public final class Chat extends Manager {
030
031    private final EntityBareJid jid;
032
033    volatile EntityFullJid lockedResource;
034
035    Presence lastPresenceOfLockedResource;
036
037    Chat(final XMPPConnection connection, EntityBareJid jid) {
038        super(connection);
039        this.jid = jid;
040    }
041
042    public void send(CharSequence message) throws NotConnectedException, InterruptedException {
043        Message stanza = new Message();
044        stanza.setBody(message);
045        stanza.setType(Message.Type.chat);
046        send(stanza);
047    }
048
049    public void send(Message message) throws NotConnectedException, InterruptedException {
050        switch (message.getType()) {
051        case normal:
052        case chat:
053            break;
054        default:
055            throw new IllegalArgumentException("Message must be of type 'normal' or 'chat'");
056        }
057
058        Jid to = lockedResource;
059        if (to == null) {
060            to = jid;
061        }
062        message.setTo(to);
063
064        connection().sendStanza(message);
065    }
066
067    public EntityBareJid getXmppAddressOfChatPartner() {
068        return jid;
069    }
070
071    void unlockResource() {
072        lockedResource = null;
073        lastPresenceOfLockedResource = null;
074    }
075}