/*
 * Filename: WebServer.java
 *
 * Author: Joe Wang
 *
 * Copyright (c) 2003-2005 
 * The Trustees of Columbia University in the City of New York
 * Columbia University Information Technology
 *
 * This file is part of NINJa.
 *
 * NINJa is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * NINJa is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with NINJa; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * Created on September 24, 2002, 11:52 AM
 */

package edu.columbia.print.ninja.prix.display;

import java.util.*;
import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.io.*;

/**
 *
 * @author  joe
 */
public class WebServer implements Runnable {

    Callback cb;
    Stack timerPool;
    transient ServerSocketChannel channel;
    
    public static interface Callback {
        void writeText(PrintWriter writer) throws Exception;
    }

    /**
     * creates an internal webserver
     */
    public WebServer(Callback cb, Stack timerPool) throws Exception {
        this.cb=cb;
        this.timerPool=timerPool;
        channel = ServerSocketChannel.open();
        channel.configureBlocking(false);
        channel.socket().setReuseAddress(true);
//        channel.socket().setSoTimeout(10);
        channel.socket().bind(new InetSocketAddress(80));
        new Thread(this).start();
    }

    void processRequest(final SocketChannel in) throws Exception {
        final Timer timer = (Timer )timerPool.pop();
        timer.schedule(
            new TimerTask() {
                public void run() {
                    try {
                        PrintWriter writer = new PrintWriter(Channels.newWriter(in, "ascii"));
                        writer.write("HTTP/1.1 200 OK\r\n");
                        writer.write("Content-Type: text/html\r\n");
                        writer.write("\r\n");
                        writer.write("\r\n");
                        cb.writeText(writer);
                        writer.flush();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(in.socket().getInputStream()));
                        for(String line=null;(line=reader.readLine())!=null;) if(line.length()==0) break;
                        writer.close();
                    }
                    catch(Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        in.close();
                    }
                    catch(Exception e) {
                        e.printStackTrace();
                    }
                    timerPool.push(timer);
                }
            },
            0L
        );
    }
    
    public void run() {
        for(;;) {
            //                ConnectionTimeout ct = null;
            try {
                final SocketChannel in = channel.accept();
                if(in==null) {
                    Thread.sleep(100);
                    continue;
                }
                System.out.println("http:"+in.socket().getRemoteSocketAddress());
                processRequest(in);
            }
            catch(SocketException e) {
                System.out.println("http timeout");
            }
            catch(java.security.AccessControlException e) {
                //					if(ct!=null) ct.interrupt();
                System.out.println("HTTP: "+e.getMessage());
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
    
}
