class User
	include Mongoid::Document

    embeds_many :accounts
    accepts_nested_attributes_for :accounts

    index({ 'accounts.jid' => 1 })

    def update_pass(jid, pass)
        account_credentials = accounts.detect do |f|
            f[:jid] == jid || f['jid'] == jid
        end

        account_credentials[:pass] = pass
        save
    end

    def self.existing_jid(jid)
        where('accounts.jid' => jid).only(:accounts).first
    end

    def self.create_jid(jid)
        new_user = new()
        new_user.add_account(jid)
        new_user.save
        new_user
    end

    def add_account(another_jid, password = nil)
        accounts << Account.new(jid: another_jid, pass: password)
        save
    end

    def self.crendentials_for_token(token)
        found = Token.where(token: token).only(:user_id).limit(1).first
        if found
            user_id = found.user_id
        else
            return []
        end

        user = where(id: user_id).only(:accounts).first
        return user ? user.accounts : []
    end

    def self.can_save_conversation(my_jid, friend_jid, chat_id = nil)

    end
end