
import java.util.logging.Logger;
import java.util.List;
import java.io.*;
 
import javax.servlet.*;
//import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.*;





//@WebFilter("/*")
public class AuthorizationResponseFilter implements Filter
{
   private static final Logger LOGGER = Logger.getLogger("ResponseFilter");
   private static final AuthorizationResponseSettings settings = AuthorizationResponseSettings.getInstance("authpolicy.properties");


   @Override
   public void init(FilterConfig filterConfig) throws ServletException
   {
      LOGGER.info("trace");
   }







   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException
   {
      LOGGER.info("trace");

      chain.doFilter(request, response);

      if(response instanceof PubdidResponseWrapper)
      {
         PubdidResponseWrapper pw = (PubdidResponseWrapper) response;
         LOGGER.info("after doFilter : " + pw.getPubdidArr().length);

         //if (pubdidWrapper.getContentType().contains("text/plain"))
         {
            String[] pubdidArr = pw.getPubdidArr();

            AuthPolicy auth = null;
            try
            {
               HttpServletRequest req = (HttpServletRequest) request;
               auth = new AuthPolicy(req.getUserPrincipal());
            }
            catch(IllegalArgumentException ex)
            {
               throw new IllegalArgumentException("Authorization : UserPrincipal is not of expected type");
            }

            pw.setAuth(auth);
            String[] authorizedPubdidArr = auth.filterAuthorized(pubdidArr,
                  settings.dbConn.uri(), settings.dbConn.userName(), settings.dbConn.password());

            pw.setPubdidArr(authorizedPubdidArr);
         }
      }
      else
      {
         throw new IllegalStateException("Response is not of expected type. Cannot performs authorization check for pubdid array.");
      }
   }

   @Override
   public void destroy()
   {
      LOGGER.info("");
   }

}

