/*
 * Copyright (C) 2013-2014 Yoshinori Hayakawa <hayakawa@cite.tohoku.ac.jp>
 *
 * This program 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 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package turtlemessenger;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * not implemeted yet..
 * 
 * @author hida
 */


public class TMHttpServer {
    
    TMController controller=null ;
    HttpServer server=null ;
    ExecutorService executor ;
    
    TMHttpServer(TMController parent, int port) {
        controller = parent ;
        executor = Executors.newCachedThreadPool();
        try {
            server = HttpServer.create(new InetSocketAddress(port), 0);
            server.createContext("/", new TMFileHandler());
            server.createContext("/msg", new TMMessageHandler());
            server.createContext("/cmt", new TMCommentsHandler());
            server.createContext("/vote", new TMVoteHandler());
            server.setExecutor(executor); 
            server.start();
        } catch (IOException ex) {
            server = null ; 
        }
    }
      
    public void stopServer() {
        if (server!=null) {
            server.stop(0) ;
            executor.shutdown() ;
        }
    }
     
    private class TMFileHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange ex) throws IOException {
            String method = ex.getRequestMethod();
            if (method.equalsIgnoreCase("GET")) {          
                OutputStream os = ex.getResponseBody();
                String uri = ex.getRequestURI().toString();
                
                if (uri.equals("/")) uri = uri + "index.html" ;
                
                if (uri.endsWith(".html")) {
                    ex.getResponseHeaders().add("Content-Type", "text/html; charset=utf-8");
                } else if (uri.endsWith(".png")) {
                    ex.getResponseHeaders().add("Content-Type", "image/png");
                } else if (uri.endsWith(".css")) {
                    ex.getResponseHeaders().add("Content-Type", "text/css");
                } else if (uri.endsWith(".js")) {
                    ex.getResponseHeaders().add("Content-Type", "application/json; charset=utf-8");
                } else {
                    ex.sendResponseHeaders(404,0);
                    os.close();
                    return ;
                }

                URL location = this.getClass().getResource("html" + uri);
                InputStream fin = location.openStream();
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                byte [] buffer = new byte[8192];
                while (true) {
                    int len = fin.read(buffer);
                    if (len < 0) {
                        break;
                    }
                    bout.write(buffer, 0, len);
                }
                fin.close();
                bout.close() ;
                byte[] data = bout.toByteArray();
                
                ex.sendResponseHeaders(200, data.length);
                
                os.write(data);
                os.close();
            }
        }
        
    }
    
            
   private class TMMessageHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange ex) throws IOException {
            String method = ex.getRequestMethod();
            if (method.equalsIgnoreCase("GET")) {
                OutputStream os = ex.getResponseBody();
                String uri = ex.getRequestURI().toString();
                ex.getResponseHeaders().add("Content-Type", "application/json; charset=utf-8");
                ex.getResponseHeaders().add("Cache-Control", "no-cache,must-revalidate");               
                byte[] data ;
                if (uri.endsWith("/msg") || uri.endsWith("/msg/")) {
                    data = controller.getMessagesInJSON(100).getBytes("UTF-8");
                } else {
                    String[] cols = uri.split("/");
                    int id = Integer.parseInt(cols[cols.length-1]) ;
                    data = controller.getMessageInJSON_Id(id).getBytes("UTF-8");
                }
                ex.sendResponseHeaders(200, data.length);
                os.write(data);
                os.close();
            }
        }
    }

     private class TMCommentsHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange ex) throws IOException {
            String method = ex.getRequestMethod();
            if (method.equalsIgnoreCase("GET")) {
                OutputStream os = ex.getResponseBody();
                ex.getResponseHeaders().add("Content-Type", "application/json; charset=utf-8");
                ex.getResponseHeaders().add("Cache-Control", "no-cache,must-revalidate");
                byte[] data = controller.getCommentsInJSON().getBytes("UTF-8") ;               
                ex.sendResponseHeaders(200, data.length);
                os.write(data) ;
                os.close();
            }
        }
    }
     
    private class TMVoteHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange ex) throws IOException {
             String method = ex.getRequestMethod();
            if (method.equalsIgnoreCase("GET")) {
                OutputStream os = ex.getResponseBody();
                ex.getResponseHeaders().add("Content-Type", "application/json; charset=utf-8");
                ex.getResponseHeaders().add("Cache-Control", "no-cache,must-revalidate");
                byte[] data = controller.getVoteCountInJSON().getBytes("UTF-8") ;                
                ex.sendResponseHeaders(200, data.length);
                os.write(data) ;
                os.close();
            }            
        }
    }
}
