package org.chenyang.http.impl.bootstrap;

import org.chenyang.http.ExceptionLogger;
import org.chenyang.http.HttpServerConnection;
import org.chenyang.http.protocol.BasicHttpContext;
import org.chenyang.http.protocol.HttpCoreContext;
import org.chenyang.http.protocol.HttpService;
import java.io.IOException;

class Worker implements Runnable {
   private final HttpService httpservice;
   private final HttpServerConnection conn;
   private final ExceptionLogger exceptionLogger;

   Worker(HttpService httpservice, HttpServerConnection conn, ExceptionLogger exceptionLogger) {
      this.httpservice = httpservice;
      this.conn = conn;
      this.exceptionLogger = exceptionLogger;
   }

   public HttpServerConnection getConnection() {
      return this.conn;
   }

   public void run() {
      try {
         BasicHttpContext localContext = new BasicHttpContext();
         HttpCoreContext context = HttpCoreContext.adapt(localContext);

         while(!Thread.interrupted() && this.conn.isOpen()) {
            this.httpservice.handleRequest(this.conn, context);
            localContext.clear();
         }

         this.conn.close();
      } catch (Exception ex) {
         this.exceptionLogger.log(ex);
      } finally {
         try {
            this.conn.shutdown();
         } catch (IOException ex) {
            this.exceptionLogger.log(ex);
         }

      }

   }
}
