/*
 * Servlet for receiving upload photos from web form.
 * 
 * $Id: PhotoUpload.java,v 1.9 2003/04/08 02:55:32 davis Exp $
 * 
 * Copyright (C) 2001  Guy Davis
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser Public License for more details.

 * You should have received a copy of the GNU Lesser Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  
 * 02111-1307, USA.
 */

package ca.guydavis.site;


import java.io.*;
import java.util.Hashtable;
import java.sql.*;
import javax.servlet.*;
import javax.swing.ImageIcon;
import javax.servlet.http.*;
import com.oreilly.servlet.multipart.*;

/**
 *
 */
public class PhotoUpload extends HttpServlet
{

    public static boolean recentlyUploaded;

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException
    {
	
	try {
	    System.setProperty("java.awt.headless", "true");
	} catch (Exception e) {
	    e.printStackTrace();
	}


	try {
	    Hashtable params = new Hashtable();
	    FilePart image = null;
	    ByteArrayOutputStream byte_out = new ByteArrayOutputStream();
	    MultipartParser mp = new MultipartParser(request, 10*1024*1024);    // 10MB upload limit
	    Part part;
	    while ((part = mp.readNextPart()) != null) {  // loop through parameters
            String name = part.getName();
            if (part.isParam()) {                     // it's a parameter part
                ParamPart paramPart = (ParamPart) part;
                //System.out.println("Reading param "+ paramPart.getName() + ": "+paramPart.getStringValue()); 
                params.put(paramPart.getName(), paramPart.getStringValue());
            } else if (part.isFile()) {               // it's a file part
                //System.out.println("Reading in the file part!");
                image = (FilePart) part;
                if (image.writeTo(byte_out) <= 0) 
                    System.out.println("Failure writing to image!");
            }
	    }
	    
	    // now all parts read in; so go to work
	    if (image != null) {  // get the image file data in a byte array
		//System.out.println("image is not null!");
		String date = (String) params.get("year") + "-";
		date += (String) params.get("month") + "-";
		date += (String) params.get("day");
		//System.out.println("Date: " + date);

        // If the "Refresh" check box was set, encourage a list refresh (slow)
        if (params.get("refresh") != null) {
            recentlyUploaded = true;
        }

		// calculate the image height and width for thumbnail
		ImageIcon imageIcon = new ImageIcon(byte_out.toByteArray());
		int thumb_height, thumb_width;
		if (imageIcon.getIconHeight() > imageIcon.getIconWidth()) {
		    thumb_height = 100;
		    thumb_width = (int) ((float)imageIcon.getIconWidth() / (float) imageIcon.getIconHeight() * 100);
		} else {
		    thumb_width = 100;
		    thumb_height = (int) ((float)imageIcon.getIconHeight() / (float) imageIcon.getIconWidth() * 100);
		} 

		try { 
		    Connection con = WebUtils.getConnection();
		    String st = "INSERT INTO photos (location, description, date_shot, filename, mimetype, img_data, ";
		    st += "height, width, thumb_height, thumb_width, category, access, title) ";
		    st += "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
		    PreparedStatement stmnt = con.prepareStatement(st);
		    stmnt.setString(1, ((String) params.get("location")));
		    stmnt.setString(2, ((String) params.get("description")));
		    stmnt.setString(3, date);
		    stmnt.setString(4, (image.getFileName()));
		    stmnt.setString(5, image.getContentType());
		    stmnt.setBytes(6, byte_out.toByteArray());
		    stmnt.setInt(7, imageIcon.getIconHeight());
		    stmnt.setInt(8, imageIcon.getIconWidth());
		    stmnt.setInt(9, thumb_height);
		    stmnt.setInt(10, thumb_width);
		    stmnt.setInt(11, Integer.parseInt((String) params.get("category")));
		    stmnt.setString(12, (String) params.get("access"));
		    stmnt.setString(13, ((String) params.get("title"))); 
		    stmnt.executeUpdate();
		} catch (SQLException e) {
		    e.printStackTrace();
		}
	    }
	    
	    // all done so, redirect back to photos
	    response.sendRedirect("/photos/");
	} catch (IOException e) {
	    e.printStackTrace();
	}
    }
}

