package com.eactive.eai.adapter.socket2.protocol.stream;

import org.apache.mina.common.IoSession;
import org.apache.mina.handler.StreamIoHandler;

import java.io.*;


public class StreamFixedHandler extends StreamIoHandler {
    protected void processStreamIo(IoSession session, InputStream in, OutputStream out) {
        // You *MUST* execute stream I/O logic in a separate thread.
        new Worker(in, out).start();
    }

    private static class Worker extends Thread {
        private final InputStream in;
        private final OutputStream out;

        public Worker(InputStream in, OutputStream out) {
            setDaemon(true);
            this.in = in;
            this.out = out;
        }

        @Override
        public void run() {
        	
        	try (
        		BufferedReader reader = new BufferedReader(new InputStreamReader(this.in));
        		PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(this.out)));
			){
//            String url;
//            Map<String, String> headers = new TreeMap<String, String>();
//            BufferedReader in = new BufferedReader(new InputStreamReader(this.in));
//            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(this.out)));
//
//            try {
//                // Get request URL.
//                url = in.readLine().split(" ")[1];
//
//                // Read header
//                String line;
//                while ((line = in.readLine()) != null && !line.equals("")) {
//                    String[] tokens = line.split(": ");
//                    headers.put(tokens[0], tokens[1]);
//                }
//
//                // Write header
//                out.println("HTTP/1.0 200 OK");
//                out.println("Content-Type: text/html");
//                out.println("Server: MINA Example");
//                out.println();
//
//                // Write content
//                out.println("<html><head></head><body>");
//                out.println("<h3>Request Summary for: " + url + "</h3>");
//                out
//                        .println("<table border=\"1\"><tr><th>Key</th><th>Value</th></tr>");
//
//                Iterator it = headers.entrySet().iterator();
//                while (it.hasNext()) {
//                    Entry e = (Entry) it.next();
//                    out.println("<tr><td>" + e.getKey() + "</td><td>"
//                            + e.getValue() + "</td></tr>");
//                }
//
//                out.println("</table>");
//
//                for (int i = 0; i < 1024; i++) {
//                    out.println("this is line: " + i + "<br/>");
//                }
//
//                out.println("</body></html>");
        		writer.flush();
        	} catch (Exception e) {
//                System.out.println("Error");
            }
        }
    }
}
