package org.iri_research.renkan.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component
public class VersionHandlerInterceptor extends HandlerInterceptorAdapter {
    
    @SuppressWarnings("unused")
    private final Logger logger = LoggerFactory
            .getLogger(VersionHandlerInterceptor.class);
    
    private static String version = null;
    
    @Override
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        if(modelAndView != null) {
            if(version == null) {
                ServletContext context = request.getServletContext();
                InputStream inputStream = context.getResourceAsStream("/META-INF/MANIFEST.MF");
                if(inputStream != null) {
                    try {
                        Manifest manifest = new Manifest(inputStream);
                        Attributes att = manifest.getMainAttributes();
                        version = att.getValue("Implementation-Version");
                    }
                    catch(IOException e) {
                        version = "N/A";
                    }
                }
                if(version == null) {
                    version = "NULL";
                }
                else if (version == "") {
                    version = "EMPTY";
                }
            }
            modelAndView.addObject("version", version);
        }
    }
}
