package ie.ucd.sumac.webportal;

import com.sun.grizzly.http.servlet.ServletAdapter;
import com.sun.grizzly.tcp.ActionCode;
import com.sun.grizzly.tcp.Response;
import com.sun.grizzly.tcp.http11.GrizzlyRequest;
import com.sun.grizzly.tcp.http11.GrizzlyResponse;
import com.sun.grizzly.util.buf.ByteChunk;
import com.sun.grizzly.util.http.MimeType;
import org.apache.log4j.Category;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;

public class SumacServletAdapter extends ServletAdapter {
    private boolean handleStatic = false;
    private String rootPath;
    private static final Category log = Logger.getLogger(SumacServletAdapter.class);

    public SumacServletAdapter(String path) {
        super();
        this.rootPath = path;
    }

    public SumacServletAdapter() {
        super();
    }

    @Override
    public void service(GrizzlyRequest request, GrizzlyResponse response) {
        String uri = request.getRequestURI();
        if (!uri.startsWith(getContextPath() + getServletPath())) {
            if (!handleStatic) {
                response.setStatus(404);
                return;
            } else {
                if ("/".equals(uri))
                    uri += "index.html";

                InputStream in = SumacServletAdapter.class.getResourceAsStream(rootPath+uri);
                if (in == null) {
                    response.setStatus(404);
                    return;
                }
                byte b[] = new byte[8192];
                ByteChunk chunk = new ByteChunk();
                Response res = response.getResponse();
                res.setStatus(200);
                int dot = uri.lastIndexOf(".");
                if (dot > 0) {
                    String ext = uri.substring(dot + 1);
                    String ct = MimeType.get(ext);
                    if (ct != null) {
                        res.setContentType(ct);
                    }
                } else {
                    res.setContentType(MimeType.get("html"));
                }

                try {
                    res.sendHeaders();


                    int rd;
                    while ((rd = in.read(b)) > 0) {
                        chunk.setBytes(b, 0, rd);
                        res.doWrite(chunk);
                    }
                    try {
                        request.getRequest().action(ActionCode.ACTION_POST_REQUEST, null);
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                    res.finish();

                } catch (IOException e) {
                    res.setStatus(500);
                    log.error("Cannot read input stream: ",e);
                }
                return;
            }
        }
        super.service(request, response);
    }

    @Override
    public void setHandleStaticResources(boolean handle) {
        this.handleStatic = handle;
    }

}