/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sample;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;

import com.sun.grizzly.comet.CometContext;
import com.sun.grizzly.comet.CometEngine;
import com.sun.grizzly.comet.CometEvent;
import com.sun.grizzly.comet.CometHandler;

public class TTTComet extends HttpServlet {

    private String contextPath = null;
    private static TTTGame game = new TTTGame();

    private class TTTHandler implements CometHandler<HttpServletResponse> {

        private HttpServletResponse response;

        public void onInitialize(CometEvent event) throws IOException {
        }

        public void onInterrupt(CometEvent event) throws IOException {
            removeThisFromContext();
        }

        public void onTerminate(CometEvent event) throws IOException {
            removeThisFromContext();
        }

        public void attach(HttpServletResponse attachment) {
            this.response = attachment;
        }

        private void removeThisFromContext() throws IOException {
            response.getWriter().close();
            CometContext context =
                    CometEngine.getEngine().getCometContext(contextPath);
            context.removeCometHandler(this);
        }

        public void onEvent(CometEvent event) throws IOException {
            if (CometEvent.NOTIFY == event.getType()) {
                PrintWriter writer = response.getWriter();
                writer.write("<script type='text/javascript'>parent.chImg(" + game.getJSON() + ")</script>\n");
                writer.flush();
                event.getCometContext().resumeCometHandler(this);
            }
        }
    }

    @Override
    public void init(ServletConfig config)
            throws ServletException {
        ServletContext context = config.getServletContext();
        contextPath = context.getContextPath() + "/TTTComet";

        CometEngine engine = CometEngine.getEngine();

        CometContext cometContext = engine.register(contextPath);
        cometContext.setExpirationDelay(120 * 1000);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        TTTHandler handler = new TTTHandler();
        handler.attach(response);

        CometEngine engine = CometEngine.getEngine();
        CometContext context = engine.getCometContext(contextPath);

        context.addCometHandler(handler);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int cell = -1;
        String cellStr = request.getParameter("cell");
        PrintWriter writer = response.getWriter();
        writer.println("cell is '" + cellStr + "'");
        if (cellStr == null) {
            writer.println("error - cell not set");
            return;
        }
        try {
            cell = Integer.parseInt(cellStr);
        } catch (NumberFormatException nfe) {
            writer.println("error - cellStr not an int: " + cellStr);
            return;
        }
        if (!game.turn(cell)) {
            writer.println("warning - invalid move");
        }
        writer.println(game.getJSON());

        CometEngine engine = CometEngine.getEngine();
        CometContext context = engine.getCometContext(contextPath);
        context.notify(null);

        // Hideous hack, not threadsafe
        if (game.win() != -1) {
            try {
                Thread.sleep(2000); // sleep 2 sec
            } catch (InterruptedException ie) {
            }
            game = new TTTGame();
        }
    }
}