package resources;

import com.google.common.collect.ImmutableMap;
import io.dropwizard.auth.Auth;
import objects.Team;
import objects.User;
import repositories.TeamsRepository;

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.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Optional;

@Singleton
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public class UtilResource
{

    private TeamsRepository teamsRepository;

    @Inject
    public UtilResource(TeamsRepository teamsRepository)
    {
        this.teamsRepository = teamsRepository;
    }

    @GET
    @Path("/whoami")
    public ImmutableMap<Object, Object> getUserData(@Auth User user)
    {
        ImmutableMap.Builder<Object, Object> responseBuilder = ImmutableMap.builder();
        String userName = user.getName();
        responseBuilder.put("userName", userName);
        Optional<Team> team = teamsRepository.getTeamByUserName(userName);
        if (team.isPresent()) {
            responseBuilder.put("teamName", team.get().getName());
        }
        return responseBuilder.build();
    }

    //todo: cleanup
    @GET
    @Path("/auth")
    public Response auth(@Auth User user)
    {
        String jsRedirect = "<script type=\"text/javascript\">\n" +
                "<!--\n" +
                "window.location = \"/page/#/tasks\"\n" +
                "//-->\n" +
                "</script>";
        return Response.ok().entity(jsRedirect).header(HttpHeaders.CONTENT_TYPE, "text/html").build();
    }
}
