package com.telephoners.krakyournet.ctf.resources;

import com.google.common.collect.ImmutableMap;
import com.telephoners.krakyournet.ctf.beans.Team;
import com.telephoners.krakyournet.ctf.beans.User;
import com.telephoners.krakyournet.ctf.repositories.TeamsRepository;
import io.dropwizard.auth.Auth;
import org.apache.commons.io.FileUtils;

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

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

    private TeamsRepository teamsRepository;

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

    @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()) {
            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
    {
        String redirectHtml = new String(FileUtils.readFileToByteArray(new File("service/src/main/resources/assets/redirect.html")));
        return Response.ok()
                .entity(redirectHtml)
                .header(HttpHeaders.CONTENT_TYPE, "text/html")
                .header(HttpHeaders.WWW_AUTHENTICATE, "Basic")
                .build();
    }
}
