package oasis.jongo.authn;

import static com.google.common.base.Preconditions.*;

import javax.inject.Inject;

import org.jongo.Jongo;
import org.jongo.MongoCollection;

import com.google.common.base.Strings;

import oasis.model.accounts.Account;
import oasis.model.accounts.AccountRepository;
import oasis.model.accounts.Token;
import oasis.model.authn.TokenRepository;

public class JongoTokenRepository implements TokenRepository {
  private final Jongo jongo;

  private final AccountRepository accountRepository;

  @Inject JongoTokenRepository(Jongo jongo, AccountRepository accountRepository) {
    this.jongo = jongo;
    this.accountRepository = accountRepository;
  }

  protected MongoCollection getAccountCollection() {
    return jongo.getCollection("account");
  }

  @Override
  public Token getToken(String tokenId) {
    checkArgument(!Strings.isNullOrEmpty(tokenId));

    Account account = accountRepository.getAccountByTokenId(tokenId);

    for(Token t : account.getTokens()) {
      if (t.getId().equals(tokenId)) {
        return t;
      }
    }

    return null;
  }

  public boolean registerToken(String accountId, Token token) {
    checkArgument(!Strings.isNullOrEmpty(accountId));
    checkNotNull(token);

    // Add the new access token in mongo
    return this.getAccountCollection().update("{id:#},{$ne: {tokens.id:#}", accountId, token.getId()).with("{$push:{tokens:#}}", token).getN() > 0;
  }

  public boolean revokeToken(String tokenId) {
    checkArgument(!Strings.isNullOrEmpty(tokenId));

    return this.getAccountCollection()
        .update("{ tokens.id: # }", tokenId)
        .with("{ $pull: { tokens: { $or: [ { id: # }, { refreshTokenId: # } ] } } }", tokenId, tokenId)
        .getN() > 0;
  }
}

@@ -245,55 +245,8 @@
 nt;%0A
-import oasis.model.accounts.AccountRepository;%0A
 impo
@@ -418,213 +418,74 @@
 %0A%0A  
-private final AccountRepository accountRepository;%0A%0A  @Inject JongoTokenRepository(Jongo jongo, AccountRepository accountRepository) %7B%0A    this.jongo = jongo;%0A    this.accountRepository = accountRepository
+@Inject JongoTokenRepository(Jongo jongo) %7B%0A    this.jongo = jongo
 ;%0A  
@@ -646,61 +646,8 @@
 ) %7B%0A
-    checkArgument(!Strings.isNullOrEmpty(tokenId));%0A%0A
     
@@ -668,74 +668,167 @@
 t = 
-a
+getA
 ccount
-Repository.getAccountByTokenId(tokenId);%0A%0A    for(Token t :
+Collection()%0A        .findOne(%22%7Btokens.id: #%7D%22, tokenId)%0A        .projection(%22%7Btokens.$: 1%7D%22)%0A        .as(Account.class);%0A%0A    if (account == null %7C%7C
  acc
@@ -847,53 +847,53 @@
 ns()
-) %7B%0A      if (t.getId().equals(tokenId
+ == null %7C%7C account.getTokens().isEmpty(
 )) %7B%0A
-  
     
@@ -905,13 +905,14 @@
 urn 
-t;%0A  
+null;%0A
     
@@ -921,26 +921,41 @@
     
-%7D%0A%0A    return null
+return account.getTokens().get(0)
 ;%0A  

Delete the AccountRepository dependency in the JongoTokenRepository.