/*
 * ImageUploader.java
 *
 * Created on 28 de julio de 2004, 1:18
 */

package com.fenalco.servlets.supplier;

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 javax.servlet.http.HttpSession;

import com.fenalco.entities.User;
import com.fenalco.utilities.MessageBuilder;

/**
 * 
 * @author Mario Linares Vásquez
 * @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
	{

		HttpSession session = request.getSession(false);
		RequestDispatcher dispatcher;

		String url;
		String message;


		//Validación de sesión
	    try
	    {
	        if( session == null || ( User )session.getAttribute( "user" ) == null || ( ( User )session.getAttribute( "user" ) ).getRoleId() != 2 )
			{
				url = "/logout";
				//message = "Sesión no iniciada";
				message = MessageBuilder.buildMessage(15);
			}
			else
			{

				String contentType = request.getContentType();
				String superOffer = (String) request.getSession().getAttribute("id");
				//System.out.println("Content type is :: " +contentType);
		
				if( (contentType != null) )
				{// && (contentType.indexOf("multipart/form-data") >= 0)) {
					String prefixFile = getServletContext().getRealPath(
							"/images/superoffer/");
					//String prefixFile = "c:\\";
		
					request.getSession().removeAttribute("id");
		
					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 + "/"
							+ superOffer + ".gif");
					fileOut.write(dataBytes, startPos, (endPos - startPos));
					fileOut.flush();
					fileOut.close();
		
					//System.out.println("File saved as " +superOffer);
					url = "/proveedor/actualizarsuperofertaproveedor?key="
							+ superOffer;
					//String url = "/proveedor/superofertasproveedor";
		
					/*
					 * RequestDispatcher dispatcher =
					 * getServletContext().getRequestDispatcher( url );
					 * dispatcher.forward(request, response);
					 */
					response.sendRedirect(response.encodeRedirectURL(url));
				}
			}
		}
	    catch( Exception e )
	    {
	        url="/logout";
	        message = MessageBuilder.buildMessage(15);
	        
			request.setAttribute("message", message);
			dispatcher = getServletContext().getRequestDispatcher(url);
			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);
	}

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

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

}