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.Repository;
import com.telephoners.krakyournet.ctf.repositories.UserRepository;

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

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

    @Inject
    public RegistrationResource(final UserRepository userRepository,
                                final Repository<Team> teamsRepository)
    {
        //todo: checkNotNUll
        this.teamsRepository = teamsRepository;
        this.userRepository = userRepository;
    }

    @GET
    @Path("/team")
    public String registerTeam(@QueryParam("teamName") final String teamName)
    {
        //todo: check if exists
        Team team = new Team();
        team.setName(teamName);
        team.setDescription("descr");

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

    @GET
    @Path("/user")
    public String register(@QueryParam("userName") final String userName,
                           @QueryParam("teamId") final String teamId)
    {
        validateTeam(teamId);
        validateUserName(userName);

        User user = new User();
        user.setEmail("gpietrusza@gmail.com");
        user.setName(userName);
        user.setPassword("password");
        user.setAdmin(false);
        user.setTeamId(teamId);
        userRepository.add(user);

        return user.getId();
    }

    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);
    }
}
