package chapter12;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.Calendar;

public class StopGamesFilter extends HttpServlet implements Filter {
    private FilterConfig filterConfig;
    private int starthour = 0;
    private int stophour = 24;
    //Handle the passed-in FilterConfig
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        String tpString;
        if ((tpString = filterConfig.getInitParameter("starthour")) != null) {
            starthour = Integer.parseInt(tpString, 10);
        }
        if ((tpString = filterConfig.getInitParameter("stophour")) != null) {
            stophour = Integer.parseInt(tpString, 10);
        }
        this.filterConfig = filterConfig;
    }

    //Process the request/response pair
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filterChain) {
        Calendar myCal = Calendar.getInstance();
        int curhour = myCal.get(Calendar.HOUR_OF_DAY);
        filterConfig.getServletContext().log("in StopGamesFilter cur:" +
                                             curhour
                                             + ", start: " + starthour +
                                             ", end: " + stophour
                );
        try {
            if ((curhour >= stophour) || (curhour <= starthour)) {
                response.setContentType("text/html;charset=GBK");
                PrintWriter out = response.getWriter();
                out.println("<html><head></head><body>");
                out.println
                        (
                                "<h1>对不起, 此时不允许玩游戏!</h1>");
                out.println("</body></html>");

                out.flush();
                filterConfig.getServletContext().log(
                        "Access to game page denied");
                return;
            }
            filterConfig.getServletContext().log("Access to game page granted");
            filterChain.doFilter(request, response);
            filterConfig.getServletContext().log(
                    "Getting out of StopGamesFilter");
        } catch (ServletException sx) {
            filterConfig.getServletContext().log(sx.getMessage());
        } catch (IOException iox) {
            filterConfig.getServletContext().log(iox.getMessage());
        }
    }

    //Clean up resources
    public void destroy() {
    }
}
