package org.gcube.application.geoportal.service.rest;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

@Path("docs")
@Slf4j
public class DocsGenerator {

    @GET
    @Path("/{any: .*}")
    public InputStream toDoc(@Context HttpServletRequest req) throws WebApplicationException {
        log.info(DocsGenerator.class.getSimpleName() + " toDoc called");

        String pathInfo = req.getPathInfo();
        log.debug("pathInfo {}", pathInfo);
        try {

            if (pathInfo.endsWith("/docs/")) {
                pathInfo += "index.html";
            }

            log.info("going to {}", pathInfo);

            String realPath = req.getServletContext().getRealPath(pathInfo);
            return new FileInputStream(new File(realPath));

        } catch (Exception e) {
            //MANAGE THE EXCEPTION
            log.error("Unexpected exception ",e);
            throw new WebApplicationException("Unexpected Exception : "+e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
}
