class WsController < WebsocketRails::BaseController

    protected

    def find_client(client_jid)
        connection_store[:clients].find do |client|
            client.jid.strip.to_s == client_jid
        end
    end

    def find_client_jid(client_jid)
        client = find_client(client_jid)
        client.jid.strip.to_s
    end

    def multichats_owner
        chats_owner = {}
        connection_store[:clients].each do |client|
            connection_store[:opened_chats][client].each do |chat_id, contacts|
                if contacts[:owner] == client.jid.strip.to_s
                    chats_owner[client] = chat_id
                end
            end
        end

        chats_owner
    end

    def kick_from_multichat2(kick)
        chats = multichats_owner()
        chats.each do |client, chat_id|
            contacts = connection_store[:opened_chats][client][chat_id][:attendants]
            contacts -= [kick]

            if contacts.empty?
                connection_store[:opened_chats][client].delete(chat_id)
                send_message 'app.chat.destroyMultichat', chat_id: chat_id
            else
                contacts.each do |contact|
                    client.send(MessageBuilder::send_multichat_contacts(client.jid.strip.to_s, contact, chat_id, contacts))
                end

                sync_contacts_frontend(MessageBuilder::send_multichat_contacts('', client.jid.strip.to_s, chat_id, contacts), chat_id)
            end
        end
    end

    def sync_contacts_frontend(message, chat_id)
        contacts = xml_contacts_to_array(message.first_element('synced_contacts'))

        send_message 'app.chat.updateSyncedContacts',
                     me: message.to.strip.to_s,
                     contacts: contacts,
                     owner: message.from.strip.to_s,
                     chat_id: chat_id
    end

    def xml_contacts_to_array(xml_contacts)
        xml_contacts.get_elements('contact').map do |contact|
            contact.text
        end
    end
end