package org.wikiwebserver.handler.echo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

import org.wikiwebserver.core.interfaces.ConnectionHandler;
import org.wikiwebserver.core.interfaces.HandlerConfiguration;

public class EchoHandler implements ConnectionHandler {
    
    private Socket sock;
    private long startTime;
    private BufferedReader reader = null;
    private OutputStream out = null;

    public void handle(Socket sock) {
        this.startTime = System.currentTimeMillis();
        this.sock = sock;
        
        try {
            reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            out = sock.getOutputStream();
            
            String line = reader.readLine();
            while (line != null) {
                out.write((line+"\r\n").getBytes());
                line = reader.readLine();
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            forceClose();
        }
    }
    
    public void gracefulClose() {
        try {
            out.write("\nConnection will close shortly.\n".getBytes());
        } catch (IOException ex) {
            forceClose();
        }
    }

    public void forceClose() {
        //  Close the connection, we are done
        try { out.close(); } catch (Exception ex) {}           
        try { reader.close(); } catch (Exception ex) {}  
        try { sock.close(); } catch (Exception ex) {}  
    }    

    public long getExecutionTime() {
        return System.currentTimeMillis() - startTime;
    }    

    public void forceStop() {
        forceClose();
        // Will always cause thread to stop
    }

    public void configure(HandlerConfiguration config) {
        
    }
}

