package org.gcube.keycloak.avatar;

import java.io.InputStream;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;

import org.jboss.resteasy.annotations.cache.NoCache;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.models.KeycloakSession;
import org.keycloak.services.resources.RealmsResource;

public class AvatarResource extends AbstractAvatarResource {

//    public static final String STATE_CHECKER_ATTRIBUTE = "state_checker";
//    public static final String STATE_CHECKER_PARAMETER = "stateChecker";

    public AvatarResource(KeycloakSession session) {
        super(session);
    }

    @Path("/admin")
    public AvatarAdminResource admin() {
        AvatarAdminResource service = new AvatarAdminResource(session);
        ResteasyProviderFactory.getInstance().injectProperties(service);
        service.init();
        return service;
    }

    @GET
    @Produces({ "image/png", "image/jpeg", "image/gif" })
    public Response downloadCurrentUserAvatarImage() {
        if (auth == null) {
            logger.debug("Unhautorized call to get avatar");
            throw new NotAuthorizedException("Bearer");
        }
        logger.debugf("Getting avatar for user %s in realm %s", auth.getUser(), auth.getSession().getRealm());
        return fetchAndCreateResponse(auth.getSession().getRealm(), auth.getUser());
    }

    @POST
    @NoCache
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadCurrentUserAvatarImage(MultipartFormDataInput input, @Context UriInfo uriInfo) {
        if (auth == null) {
            throw new NotAuthorizedException("Bearer");
        }

//        if (!isValidStateChecker(input)) {
//            throw new ForbiddenException("State");
//        }

        logger.debugf("Uploading new avatar for user %s in realm %s", auth.getUser(), auth.getSession().getRealm());
        Response response = null;
        try {
            InputStream imageInputStream = input.getFormDataPart(AVATAR_IMAGE_PARAMETER, InputStream.class, null);

            saveUserImage(auth.getSession().getRealm(), auth.getUser(), imageInputStream);

            if (uriInfo.getQueryParameters().containsKey("account")) {
                UriBuilder uriBuilder = RealmsResource.accountUrl(session.getContext().getUri().getBaseUriBuilder());
                for (String parameterName : uriInfo.getQueryParameters().keySet()) {
                    List<String> parameterValues = uriInfo.getQueryParameters().get(parameterName);
                    for (String parameterValue : parameterValues) {
                        uriBuilder.queryParam(parameterName, parameterValue);
                    }
                }
                response = Response.seeOther(uriBuilder.build(auth.getSession().getRealm().getName())).build();
            } else {
                response = Response.ok().build();
            }
        } catch (Exception ex) {
            response = Response.serverError().build();
        }
        return response;
    }

//    private boolean isValidStateChecker(MultipartFormDataInput input) {
//        try {
//            String actualStateChecker = input.getFormDataPart(STATE_CHECKER_PARAMETER, String.class, null);
//            String requiredStateChecker = (String) session.getAttribute(STATE_CHECKER_ATTRIBUTE);
//
//            return Objects.equals(requiredStateChecker, actualStateChecker);
//        } catch (Exception ex) {
//            return false;
//        }
//    }

}