package org.luxons.sevenwonders.repositories;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.luxons.sevenwonders.errors.UserInputException;
import org.luxons.sevenwonders.game.Lobby;
import org.luxons.sevenwonders.game.Player;
import org.luxons.sevenwonders.game.data.GameDefinitionLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class LobbyRepository {

    private final GameDefinitionLoader gameDefinitionLoader;

    private Map<String, Lobby> lobbies = new HashMap<>();

    private Map<Long, Lobby> lobbiesById = new HashMap<>();

    private long lastGameId = 0;

    @Autowired
    public LobbyRepository(GameDefinitionLoader gameDefinitionLoader) {
        this.gameDefinitionLoader = gameDefinitionLoader;
    }

    public Collection<Lobby> list() {
        return lobbies.values();
    }

    public Lobby create(String gameName, Player owner) {
        if (lobbies.containsKey(gameName)) {
            throw new GameNameAlreadyUsedException(gameName);
        }
        long id = lastGameId++;
        Lobby lobby = new Lobby(id, gameName, owner, gameDefinitionLoader.getGameDefinition());
        lobbies.put(gameName, lobby);
        lobbiesById.put(id, lobby);
        return lobby;
    }

    public Lobby find(long lobbyId) {
        Lobby lobby = lobbiesById.get(lobbyId);
        if (lobby == null) {
            throw new LobbyNotFoundException(String.valueOf(lobbyId));
        }
        return lobby;
    }

    public static class LobbyNotFoundException extends RuntimeException {
        LobbyNotFoundException(String name) {
            super("Lobby not found for game '" + name + "'");
        }
    }

    private static class GameNameAlreadyUsedException extends UserInputException {
        GameNameAlreadyUsedException(String name) {
            super("Game name '" + name + "' already exists");
        }
    }
}

@@ -122,66 +122,8 @@
 p;%0A%0A
-import org.luxons.sevenwonders.errors.UserInputException;%0A
 impo
@@ -161,16 +161,16 @@
 .Lobby;%0A
+
 import o
@@ -492,67 +492,8 @@
 r;%0A%0A
-    private Map%3CString, Lobby%3E lobbies = new HashMap%3C%3E();%0A%0A
     
@@ -524,20 +524,16 @@
  lobbies
-ById
  = new H
@@ -870,125 +870,8 @@
 ) %7B%0A
-        if (lobbies.containsKey(gameName)) %7B%0A            throw new GameNameAlreadyUsedException(gameName);%0A        %7D%0A
     
@@ -1018,50 +1018,8 @@
 put(
-gameName, lobby);%0A        lobbiesById.put(
 id, 
@@ -1126,12 +1126,8 @@
 bies
-ById
 .get
@@ -1388,32 +1388,32 @@
 (String name) %7B%0A
+
             supe
@@ -1477,221 +1477,7 @@
    %7D
-%0A%0A    private static class GameNameAlreadyUsedException extends UserInputException %7B%0A        GameNameAlreadyUsedException(String name) %7B%0A            super(%22Game name '%22 + name + %22' already exists%22);%0A        %7D%0A    %7D
 %0A%7D%0A

Remove unicity constraint on game names