/*
 * 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 superOfferId = ( ( Integer ) request.getSession().getAttribute("superOfferId") ).toString();
                                //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("superOfferId");

                                    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);
                                    int lastIndex = contentType.lastIndexOf("=");
                                    String boundary = contentType.substring(lastIndex + 1, contentType.length());

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

                                    String extension=file.substring(pos2, pos3);

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

                                    String fileUrl = prefixFile + "/" + superOfferId + "."+ extension;

                                    System.out.println( fileUrl + " " );

                                    FileOutputStream fileOut = new FileOutputStream(fileUrl);
                                    fileOut.write(dataBytes, startPos, (endPos - startPos));
                                    fileOut.flush();
                                    fileOut.close();

                                    request.setAttribute("superOfferId", superOfferId );
                                    request.setAttribute("imageUrl", superOfferId + "." +extension + "");

                                    //url = "/administrador/actividades/actualizar_actividad?key="+ activityId;
                                    url = "/proveedor/actualizarsuperofertaproveedor?operationType=updateImage";

                                    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";
	}

}