package org.atea.nlptools.macroniser.servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author University of Waikato - Te Whare Wānanga o Waikato
 * @version 2.0
 * @since   2014-11-20 
 */
public class DownloadServlet extends HttpServlet
{
    private File tmpdir;

    @Override
    public void init(ServletConfig config)
        throws ServletException
    {
        super.init(config);

        tmpdir = new File((String)config.getServletContext().getAttribute("tmpdir"));
    }

    /**
     * Configures the response to contain an error.
     * @param response The response.
     * @param statusCode The HTTP error code.
     * @param description The error description.
     * @throws IOException
     */
    private void sendError(HttpServletResponse response, int statusCode, String description)
        throws IOException
    {
        response.setStatus(statusCode);
        response.getWriter().println(description);
    }

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        String filePath = request.getParameter("filepath");
        if (filePath == null)
        {
            sendError(response, HttpStatusCode.BadRequest, "Expected a 'filepath' parameter.");
            return;
        }

        String fileName = request.getParameter("filename");
        if (fileName == null)
        {
            sendError(response, HttpStatusCode.BadRequest, "Expected a 'filename' parameter.");
            return;
        }

        final File file = new File(this.tmpdir, filePath);
        if (!file.exists())
        {
            sendError(response, HttpStatusCode.BadRequest, "The requested file is invalid.");
            return;
        }

        ServletOutputStream out = null;
        InputStream in = null;

        try
        {
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            out = response.getOutputStream();
            in = new FileInputStream(file);
            byte[] bytes = new byte[1 * 1024 * 1024];
            int bytesRead;

            while ((bytesRead = in.read(bytes)) != -1) {
                out.write(bytes, 0, bytesRead);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            out.close();
            in.close();
        }
    }
}
