package jp.sourceforge.shovel.filter;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileSystemUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.seasar.framework.container.S2Container;

import jp.sourceforge.shovel.exception.ApplicationRuntimeException;
import jp.sourceforge.shovel.exception.ErrorPage;

import static jp.sourceforge.shovel.CommonConst.*;
import static jp.sourceforge.shovel.ErrorConst.*;

public class TransactionFilterDelegete {
    S2Container container;
    static Log accessLog = LogFactory.getLog(ACCESS_LOG);

    public void doAccessLog(HttpServletRequest request) {
        accessLog.info(request.getRequestURI());
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException, ErrorPage {
        HttpServletRequest req = (HttpServletRequest)request;
        this.doAccessLog(req);

        Properties properties = this.getCommonProperties();
        String webroot = properties.getProperty(KEY_WEBROOT);
        String uri = req.getRequestURI();
        if (!uri.startsWith(webroot)) {
            String tmp = properties.getProperty(KEY_REQUIRED_DISKSPACE);
            if ( tmp != null ) {
                long requiredDiskSpace = new Long( tmp );
                if( requiredDiskSpace > 0 )
                {
                    String filesDir = properties.getProperty( KEY_FILES_DIR );
                    long freeDiskSpace = FileSystemUtils.freeSpaceKb( filesDir ) / 1024; // MB
                    if( freeDiskSpace < requiredDiskSpace )
                    {
                        ApplicationRuntimeException e = new ApplicationRuntimeException( E_COMMON_TOO_SHORT_STORAGE );
                        e.setCauseArgs( String.valueOf( requiredDiskSpace ) );
                        e.setCounterMeasureArgs( filesDir );
                        throw e;
                    }
                }
            }
        }
        chain.doFilter( request, response );
    }
    public void setContainer(S2Container container) {
        this.container = container;
    }
    public Properties getCommonProperties() {
        return (Properties)this.container.getComponent("commonProperties");
    }
}
