package dareka.processor.impl;

import java.io.IOException;
import java.util.regex.Pattern;

import dareka.common.Logger;
import dareka.extensions.RequestFilter;
import dareka.processor.HttpRequestHeader;

public class DefaultRequestFilter implements RequestFilter {
    private static final String allowDomains =
        "^(?:LOCAL" +
        "|local\\.ptron" +
        "|(.+\\.)?nicovideo\\.jp" +
        "|(.+\\.)?smilevideo\\.jp" +
        "|(.+\\.)?[ns]img\\.jp" +
        "|(.+\\.)?dmc\\.nico" +
        "|(|g-)ecx\\.images-amazon\\.com" +
        "|(.+\\.)?nicovideo\\.photozou\\.jp" +
        ")$";
    private static final Pattern allowDomainPattern
        = Pattern.compile(allowDomains);
    
    private boolean isDenyDomain(String host) {
        // [nl] niconicoMode
        if (Boolean.getBoolean("niconicoMode")) {
            boolean allow = allowDomainPattern.matcher(host).matches();
            if (allow == false) {
                Logger.warning("Forbidden host access: " + host);
                return true;
            }
        }
        return false;
    }
    
    public int onRequest(HttpRequestHeader requestHeader) throws IOException {
        // niconicoMode
        if (isDenyDomain(requestHeader.getHost()))
            return RequestFilter.DROP;
        
        // Referer‚š’¼‚·
        String referer = requestHeader.getMessageHeader("Referer");
        if (referer != null) {
            if (referer.startsWith("http://www.nicovideo.jp/cache")) {
                requestHeader.setMessageHeader("Referer", "http://www.nicovideo.jp/my");
                requestHeader.setParameter("nl-from", referer);
                requestHeader.setParameter("nl-region", "cache");
            } else if (referer.matches("http://[^/]+\\.nicovideo\\.jp/local(|/.*)")) {
                requestHeader.setMessageHeader("Referer", "http://www.nicovideo.jp/my");
                requestHeader.setParameter("nl-from", referer);
                requestHeader.setParameter("nl-region", "local");
            } else if (referer.startsWith("file://")) {
                requestHeader.setMessageHeader("Referer", "http://www.nicovideo.jp/my");
                requestHeader.setParameter("nl-from", referer);
                requestHeader.setParameter("nl-region", "local");
            }
        }
        
        return RequestFilter.OK;
    }

}
