package zall.page;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.util.Streams;

import zall.Zallery;
import zall.ZalleryServlet;
import zall.bean.Image;
import zall.bean.Media;
import zall.bean.User;
import zall.bean.Video;
import zall.manager.AuthenticationManager;
import zutil.db.DBConnection;
import zutil.io.file.FileUtil;

import static zall.page.ContentServlet.URI_IMAGE;
import static zall.page.ContentServlet.URI_VIDEO;


/**
 * A headless page that provides media content.
 */
@WebServlet({URI_IMAGE, URI_VIDEO})
public class ContentServlet extends ZalleryServlet {
    private static final long serialVersionUID = 1L;

    public static final String URI_IMAGE = "/image";
    public static final String URI_VIDEO = "/video";


    public void doGet(HttpServletRequest request, HttpServletResponse response, DBConnection db) throws ServletException, SQLException, IOException {
        String size = request.getParameter("size");

        Media media = null;
        String contentType = "";
        switch (request.getServletPath()){
            case "/video":
                media = Video.load(db, Integer.parseInt(request.getParameter("id")));
                contentType = "video";
                break;
            case "/image":
                media = Image.load(db, Integer.parseInt(request.getParameter("id")));
                contentType = "image";
                break;
        }

        if (media != null) {
            File file;
            if (size == null)
                file = media.getFile(Media.Size.ORIGINAL);
            else
                file = media.getFile(Media.Size.valueOf(size.toUpperCase()));

            if (request.getParameter("download") != null)
                response.setHeader("Content-disposition", "attachment; filename=" + media.getTitle() + "." + FileUtil.getFileExtension(file));

            if (file.exists()) {
                response.setContentType(contentType + "/" + FileUtil.getFileExtension(file));
                response.setContentLength((int) file.length());

                BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
                Streams.copy(in, response.getOutputStream(), false);
                in.close();
            } else
                response.setStatus(404);
        } else {
            // Page not found
            response.setStatus(404);
        }
    }
}
