package com.telephoners.krakyournet.ctf.resources;

import com.telephoners.krakyournet.ctf.beans.Team;
import com.telephoners.krakyournet.ctf.beans.User;
import com.telephoners.krakyournet.ctf.exceptions.ElementAlreadyExistsException;
import com.telephoners.krakyournet.ctf.exceptions.ElementDoesNotExistException;
import com.telephoners.krakyournet.ctf.repositories.TeamRepository;
import com.telephoners.krakyournet.ctf.repositories.UserRepository;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull;

@Singleton
@Path(value = "/register")
@Produces(MediaType.APPLICATION_JSON)
public class RegistrationResource
{
    private final TeamRepository teamsRepository;
    private final UserRepository userRepository;

    @Inject
    public RegistrationResource(final UserRepository userRepository,
                                final TeamRepository teamsRepository)
    {
        this.teamsRepository = checkNotNull(teamsRepository);
        this.userRepository = checkNotNull(userRepository);
    }

    @POST
    @Path("/team")
    public String registerTeam(final Team team)
    {
        validateTeamName(team.getName());

        teamsRepository.add(team);
        return team.getId();
    }

    @POST
    @Path("/user")
    public String register(final User user)
    {
        validateTeam(user.getTeamId());
        validateUserName(user.getName());

        userRepository.add(user);
        return user.getId();
    }

    private void validateTeamName(final String teamName)
    {
        if(teamsRepository.exists(teamName)) throw new ElementAlreadyExistsException(Team.class);
    }

    private void validateTeam(final String teamId)
    {
        if(teamsRepository.contains(teamId)) throw new ElementDoesNotExistException(Team.class);
    }

    private void validateUserName(final String userName)
    {
        if(userRepository.exists(userName)) throw new ElementAlreadyExistsException(User.class);
    }
}
