module MessageBuilder
    def self.build_multi_messages(message, from, attendants, 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

    def self.build_message(message, from, to)
        message = Jabber::Message.new(to, message)
        message.from = from

        message
    end

    def self.ask_for_multichat_contacts(from, to, chat_id)
        message = Jabber::Message.new(to)
        message.from = from
        sync_request = REXML::Element.new('sync_contacts_request')
        sync_request.add_attributes('chat_id' => chat_id)
        message.add_element sync_request

        message
    end

    def self.send_multichat_contacts(from, to, chat_id, contacts)
        message = Jabber::Message.new(to)
        message.from = from
        sync_answer = REXML::Element.new('synced_contacts')
        collect_contacts(sync_answer, contacts)
        sync_answer.add_attributes('chat_id' => chat_id)
        message.add_element sync_answer

        message
    end

    def self.export_multichat(from, to, chat_id, contacts)
        message = Jabber::Message.new(to)
        message.from = from
        chat = REXML::Element.new('exported_chat')
        collect_contacts(chat, contacts)
        chat.add_attributes('chat_id' => chat_id)
        message.add_element chat

        message
    end

    private

    def self.collect_contacts(to_element, contacts)
        contacts.each do |contact|
            contact_xml = REXML::Element.new('contact')
            contact_xml.text = contact
            to_element.add_element contact_xml
        end
    end
end