package com.telephoners.krakyournet.ctf.resources;

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

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 = \"http://\" + window.location.host + \"/page\"\n" +
                "//-->\n" +
                "</script>";
        return Response.ok().entity(jsRedirect).header(HttpHeaders.CONTENT_TYPE, "text/html").header(HttpHeaders.WWW_AUTHENTICATE, "Basic").build();
    }
}
