package code;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class Resources implements HttpHandler {


	@Override
	public void handle(HttpExchange exchange) throws IOException {
		String requestURI = exchange.getRequestURI().toASCIIString().replace("/secured/home/","/");

        String requestMethod = exchange.getRequestMethod();
        if (Helper.compareText(requestMethod, "GET")) {
            String response = getLocalPage(requestURI);
            if(response.equals("fail")){
                //nel caso in cui non ci sia il file (perche non stato scaricato), allora creo un file fittizzio per non far crashare tutto il resto
                String[] requestedPath = requestURI.split("/");
                // get the last element of requestedPath and remove .js
                String[] requestedPage = requestedPath[requestedPath.length-1].split("\\.");
                String className = requestedPage[0];
                // make requested page with the first letter capitalized
                className = className.substring(0, 1).toUpperCase() + className.substring(1);
                response = "class "+className+"{}\nexport default " +className;
            }
            List<String> strlist = new ArrayList<>();
            switch (requestURI.substring(1, 4)) {
	            case "js/" : strlist.add("text/javascript"); break;
	            case "css" : strlist.add("text/css"); break;
	            default : strlist.add("text"); break;
            }
            exchange.getResponseHeaders().put("content-type", strlist);
            exchange.sendResponseHeaders(200, response.getBytes().length);
            OutputStream os = exchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        } else {
            Helper.methodNotAllowed(exchange);
        }
	}

	private static String getLocalPage(String uri) {
        String page = Server.CLIENT_PATH+uri;
        StringBuilder answer = new StringBuilder();
        BufferedReader bufferedReader = null;

        try {
            FileReader fileReader = new FileReader(page);

            bufferedReader = new BufferedReader(fileReader);
            boolean isComment = false;
            String line;
            while ((line = bufferedReader.readLine()) != null) {
            	line = line.trim();
            	if((line.startsWith("/*") && line.endsWith("*/")) || line.startsWith("//")) {
            		continue;
            	}
            	if(line.startsWith("/*")) {
            		isComment = true;
            		continue;
            	}
            	if(line.endsWith("*/")) {
            		isComment = false;
            		continue;
            	}
            	if(!isComment && line.length()>0)
            		answer.append(line).append("\n");
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Unable to open file '" + page + "'");
            return "fail";
        } catch (IOException ex) {
            System.out.println("Error reading file '" + page + "'");
            return "fail";
        } finally {
            try{
                if(bufferedReader != null)
                    bufferedReader.close();
            } catch (IOException ex){
                System.out.println("Error closing bufferedReader");
            }
        }
        return answer.substring(0,answer.length()-1);
    }



}