class WsChatController < WsController

    def start_polling_messages
        connection_store[:clients].each do |client|
            client.add_message_callback do |message|
                if message.body
                    send_message 'app.chat.messageReceived',
                                 from: message.from.strip.to_s,
                                 to: message.to.strip.to_s,
                                 message: message.body,
                                 chat_id: if message.attribute(:is_simulating) then message.attribute(:chat_id) end
                end
                #TODO: upozornit na pisanie spravy
                #TODO: odoslat informaciu o tom, ze pisem spravu
                #else
                #    send_message 'app.chat.messageState',
                #                 state: message.chat_state,
                #                 from: message.from.strip.to_s,
                #                 to: message.to.strip.to_s,
                #                 message: message.body,
                #                 chat_id: if message.attribute(:is_simulating) then message.attribute(:chat_id) end
            end
        end
    end

    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