package com.rjconsultores.ventaboletos.web.utilerias.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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

import org.springframework.core.io.ClassPathResource;

/**
 * Servlet implementation class ImageServlet
 */
public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String PATH_IMAGENES = "/com/rjconsultores/ventaboletos/web/cliente/imagenes/";

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
		// Set content type
		resp.setContentType("image/png");

		String imagene = request.getParameter("imagene");
		if (imagene != null) {
			// Open the file and output streams
			InputStream in = getImagene(imagene);
			OutputStream out = resp.getOutputStream();

			// Copy the contents of the file to the output stream
			byte[] buf = new byte[1024];
			int count = 0;
			while ((count = in.read(buf)) >= 0) {
				out.write(buf, 0, count);
			}
			in.close();
			out.close();
		}
	}

	private InputStream getImagene(String imagene) {
		InputStream inputStream = null;
		try {
			inputStream = new ClassPathResource(PATH_IMAGENES + imagene).getInputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return inputStream;
	}

}
