/*
 * ImageUploader.java
 *
 * Created on 1 de octubre de 2004, 11:10
 */

package com.fenalco.servlets.sysmanager;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

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

import com.fenalco.entities.Section;
import com.fenalco.utilities.database.Transaction;

/**
 * 
 * @author Juan Ernesto Peņa Kaltekis
 * @version
 */
public class ImageUploader extends HttpServlet
{

	/**
	 * Initializes the servlet.
	 */
	public void init( ServletConfig config ) throws ServletException
	{
		super.init(config);

	}

	/**
	 * Destroys the servlet.
	 */
	public void destroy( )
	{

	}

	/**
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
	 * methods.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void processRequest( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		String contentType = request.getContentType();
		String section = (String) request.getSession()
				.getAttribute("sectionId");
		System.out.println("Content type is :: " + contentType);

		if( (contentType != null) )
		{// && (contentType.indexOf("multipart/form-data") >= 0)) {
			String prefixFile = getServletContext().getRealPath(
					"/images/sections/");
			//String prefixFile = "c:\\";

			request.getSession().removeAttribute("sectionId");

			DataInputStream in = new DataInputStream(request.getInputStream());
			int formDataLength = request.getContentLength();

			byte dataBytes[] = new byte[formDataLength];
			int byteRead = 0;
			int totalBytesRead = 0;

			while( totalBytesRead < formDataLength )
			{
				byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
				totalBytesRead += byteRead;
			}

			String file = new String(dataBytes);
			//String saveFile = file.substring(file.indexOf("filename=\"") +
			// 10);
			//saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
			//saveFile = saveFile.substring(saveFile.lastIndexOf("\\") +
			// 1,saveFile.indexOf("\""));

			int lastIndex = contentType.lastIndexOf("=");
			String boundary = contentType.substring(lastIndex + 1, contentType
					.length());

			int pos;
			pos = file.indexOf("filename=\"");
			pos = file.indexOf("\n", pos) + 1;
			pos = file.indexOf("\n", pos) + 1;
			pos = file.indexOf("\n", pos) + 1;

			int boundaryLocation = file.indexOf(boundary, pos) - 4;
			int startPos = ((file.substring(0, pos)).getBytes()).length;
			int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

			FileOutputStream fileOut = new FileOutputStream(prefixFile + "/"
					+ section + ".gif");
			fileOut.write(dataBytes, startPos, (endPos - startPos));
			fileOut.flush();
			fileOut.close();

			System.out.println("File saved as " + section);

			Section s = new Section(Integer.parseInt(section));
			Transaction transaction = new Transaction();
			s.setImage(prefixFile + "/" + section + ".gif");
			System.out.println("image-> " + s.getImage());
			s.update(transaction);
			transaction.execute();

		}

		RequestDispatcher dispatcher = request
				.getRequestDispatcher("/administrador/actualizarsecciones?key="
						+ section + "&operationType=update");
		dispatcher.forward(request, response);
	}

	/**
	 * Handles the HTTP <code>GET</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void doGet( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void doPost( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Returns a short description of the servlet.
	 */
	public String getServletInfo( )
	{
		return "Short description";
	}

}