class WsChatController < WsController

    def open_chat
        id = Time.now.to_f
        me = message[:chatOwner]
        client = find_client(me)

        connection_store[:opened_chats] = {} if ! connection_store[:opened_chats]
        connection_store[:opened_chats][client] = {} if ! connection_store[:opened_chats][client]
        connection_store[:opened_chats][client][id] = []

        trigger_success id: id
    end

    def add_to_chat
        client = find_client(message[:chatOwner])

        chat_id = message[:chatId]
        somebody = message[:jid]

        connection_store[:opened_chats][client][chat_id] << somebody
    end

    def send_chat_message
        me = message[:from]
        client = find_client(me)

        if client
            messages = build_messages(message[:message], client, message[:chatId])

            # Xmpp4r doesn't support XEP-0033 (multicast messages)
            messages.each do |message|
                client.send(message)
            end

            trigger_success message[:message]
        else
            trigger_failure
        end
    end

    private

    def build_messages(message, client_from, chat_id)
        from = client_from.jid.to_s
        attendants = connection_store[:opened_chats][client_from][chat_id]

        attendants.map do |person|
            message = Jabber::Message.new(person, message)
            message.from = from
            message.add_attribute('chat_id', chat_id)
            message.add_attribute('is_simulating', true)
            message
        end
    end
end