package siprp.pagina;

import com.evolute.utils.arrays.*;
import com.evolute.utils.strings.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import java.lang.reflect.Array;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.velocity.*;
import org.apache.velocity.app.*;

public class doPostLogin extends siprpServlet
{
    
    /** Creates a new instance of doPostLogin */
    public doPostLogin(HttpServletRequest req, HttpServletResponse res) throws IOException
    {
System.out.println( "doPostLogin()" );
        ServletOutputStream out = res.getOutputStream();
        StringBuffer dbQuery;
        ResultSet2DArray rs;
        Connection con = null ;
        Statement stmt = null ;
        String user, userRole, password;
        
        try
        {
                user = req.getParameter("user");
                password = req.getParameter("password");
            
                if (user.equals(""))
                {
                    out.println( mergeTemplate( msgErroNoUser, errorTemplate) );
                }
                else
                {
                    Class.forName(bdDriver);
                    con = DriverManager.getConnection( bdUrl, bdUsername, bdPassword );
                    dbQuery = new StringBuffer();
                    dbQuery.append( "SELECT password FROM users WHERE username = '"+user+"'");
                
                    stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                    rs = new ResultSet2DArray( stmt.executeQuery( dbQuery.toString()) );
					
					
                    if ( rs.columnLength() > 0 && password.equals((String)rs.get(0,0)))
                    {
                        // Obter Role
                    
                        dbQuery = new StringBuffer();
                        dbQuery.append( "SELECT role FROM roles WHERE username = '"+user+"'");
                        stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                    
                        rs = new ResultSet2DArray( stmt.executeQuery( dbQuery.toString()) );
                        userRole = (String)rs.get(0,0);
                    
                        // UPDATE HTTP SESSION
                        HttpSession session = req.getSession(true);
                        session.setMaxInactiveInterval(sessionTimeout);
                    
                        session.setAttribute(sessionUser, user);
                        session.setAttribute(sessionUserRole, userRole);
                        session.setAttribute(sessionPassword, password);

						HashMap hmValues = new HashMap();
						session.setAttribute( sessionEmpresaId, userRole );
						if( userRole.equals( "manager" ) )
						{
						//	session.setAttribute( sessionCompanyName, nomeEmpresa( con, "" + session.getAttribute( sessionEmpresaId ) ) );
							session.setAttribute( sessionCompanyName, null );
							session.setAttribute( sessionEstabelecimentoId, null );
						//hmValues.put( templateQuery, super.queryStringEmpresas );
							new doGetListaEmpresas( req, res );
						}
						else
						{
							session.setAttribute( sessionCompanyName, 
									nomeEmpresa( DriverManager.getConnection( bdLocalUrl, bdLocalUsername, bdLocalPassword ), 
													userRole ) );
							session.setAttribute( sessionEstabelecimentoId, "-1" );
						//hmValues.put( templateQuery, super.queryStringEstabelecimentos );
							new doGetListaEstabelecimentos( req, res );
						}
						stmt.close();
						con.close();

						hmValues.put( "empresa_nome", session.getAttribute( sessionCompanyName ) );
						hmValues.put( "empresa_id", session.getAttribute( sessionEmpresaId ) );
						hmValues.put( "estabelecimento_id", session.getAttribute( sessionEstabelecimentoId ) );
						hmValues.put( "userRole", userRole );
						hmValues.put( "userName", user );
						//out.println( mergeTemplate( hmValues, super.authenticatedUserTemplate));  
			
                        //out.println( mergeTemplate( user, userRole, super.authenticatedUserTemplate));  
                    }
                    else
                    {
                        out.println( mergeTemplate( msgErroAuthFail, super.errorTemplate) );
                    }   
                }
        
        }
        catch ( SQLException e )
        {
            e.printStackTrace();
            out.println( mergeTemplate( msgErroBd , super.errorTemplate) );
        }
        catch ( IllegalStateException e ) // session timeout
        {
            e.printStackTrace();
            out.println( mergeTemplate(msgSessionTimeout, super.errorTemplate) );
        }
        catch ( Exception e )
        {
            e.printStackTrace();
            out.println( mergeTemplate( msgGenericError , super.errorTemplate) );
        }
    }
    
}
