package org.ibai.app.webui.servlet;

import java.io.IOException;
import java.sql.SQLException;

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

import org.apache.log4j.Logger;
import org.apache.commons.lang.StringUtils;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;

import java.sql.*;
import org.dspace.core.ConfigurationManager;

public class PDStreamingServlet extends org.dspace.app.webui.servlet.DSpaceServlet
{
    private static Logger log = Logger.getLogger(PDStreamingServlet.class);

    protected void doDSGet(Context context, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException,
            SQLException, AuthorizeException
    {
    	
    	  HttpSession session = request.getSession(true);
    	  if ((isNullOrBlank((String)session.getAttribute("usuario"))) || (!"usuario".equals((String)session.getAttribute("usuario_tipo")))) response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/login"));
    		else {
    			String libro_id = "";
    			String slug = request.getParameter("libro");
    			
    			Connection conexion = null;
				 	ResultSet resultado_id = null;
				 	try {
				 			conexion = conecta();				
						  PreparedStatement  preparedStatement_id=conexion.prepareStatement("SELECT ID_LIBROS FROM PD_LIBROS WHERE SLUG='" + slug + "'");
							resultado_id = preparedStatement_id.executeQuery();
						  if (resultado_id.next()) {
						  		libro_id = resultado_id.getString("ID_LIBROS");
						  }
						  
					}
					catch(SQLException e) { }
					finally {
						if (resultado_id != null) resultado_id.close();
						if (conexion != null)  conexion.close();
					}
	    		
	    		request.setAttribute("libro", libro_id);

	    		session.setAttribute("libro_streaming", libro_id);
    			JSPManager.showJSP(request, response, "/prestamo-digital/streaming.jsp");
    		}
    }
    
   protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {
        doGet(request, response);
    }
    
    private static boolean isNullOrBlank(String param) { 
		    return param == null || param.trim().length() == 0;
		}
		
		protected static Connection conecta() { 
				try {
					String bd      = ConfigurationManager.getProperty("db.url");
					String usuario = ConfigurationManager.getProperty("db.username");
					String pass    = ConfigurationManager.getProperty("db.password");
					return DriverManager.getConnection(bd, usuario, pass); 
				}
				catch (Exception er) { return null; } 
		}

}
