package com.telephoners.krakyournet.ctf.resources;

import com.google.common.collect.ImmutableMap;
import com.telephoners.krakyournet.ctf.beans.User;
import io.dropwizard.auth.Auth;

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.io.IOException;

@Singleton
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public class UtilResource
{
    private static String redirectHtml = "<!DOCTYPE html><html lang=\"en\" ng-app=\"ctfApp\"><head></head><script type=\"text/javascript\">window.location = \"http://\" + window.location.host;</script></html>";
//    private final Repository<Team> teamsRepository;
//    private final ApplicationConfiguration applicationConfiguration;

//    @Inject
//    public UtilResource(Repository<Team> teamsRepository,
//                        ApplicationConfiguration applicationConfiguration)
//    {
//        this.teamsRepository = teamsRepository;
//        this.applicationConfiguration = applicationConfiguration;
//    }

    @GET
    @Path("/startup")
    public Response getStartupConfiguration()
    {
        return null;
//        return Response.ok().entity(applicationConfiguration.getStartupConfiguration()).build();
    }

    @GET
    @Path("/whoami")
    public Response getUserData(@Auth User user)
    {
        ImmutableMap.Builder<Object, Object> responseBuilder = ImmutableMap.builder();
        String userName = user.getName();
        responseBuilder.put("userName", userName);
        if (!user.isAdmin()) {
            //todo: fix
//            Team team = teamsRepository.getTeamByUserName(userName);
//            responseBuilder.put("teamName", team.getName());
        } else {
            responseBuilder.put("isAdmin", true);
        }
        return Response.ok()
                .entity(responseBuilder.build())
                .build();

    }

    @GET
    @Path("/auth")
    public Response auth(@Auth User user) throws IOException
    {
        return Response.ok()
                .entity(redirectHtml)
                .header(HttpHeaders.CONTENT_TYPE, "text/html")
                .header(HttpHeaders.WWW_AUTHENTICATE, "Basic")
                .build();
    }
}
