package org.gcube.application.geoportal.service;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.ext.Provider;

import org.gcube.common.authorization.library.provider.AccessTokenProvider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.utils.manager.SecretManager;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.authorization.utils.secret.GCubeSecret;
import org.gcube.common.authorization.utils.secret.JWTSecret;
import org.gcube.common.authorization.utils.secret.Secret;

import lombok.extern.slf4j.Slf4j;

@Provider
@PreMatching
@Slf4j
public class RequestFilter implements ContainerRequestFilter, ContainerResponseFilter {


    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        log.trace("PreMatching RequestFilter");

        SecretManager secretManager = new SecretManager();

        String token = AccessTokenProvider.instance.get();
        if(token!=null) {
            Secret secret = new JWTSecret(token);
            secretManager.addSecret(secret);
        }

        token = SecurityTokenProvider.instance.get();
        if(token!=null) {
            Secret secret = new GCubeSecret(token);
            secretManager.addSecret(secret);
        }

        SecretManagerProvider.instance.set(secretManager);

    }

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {
        log.trace("ResponseFilter");
        SecretManagerProvider.instance.remove();
    }

}

