/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package web;

import ejb.News;
import ejb.NewsFacade;
import ejb.Users;
import ejb.UsersFacade;
import java.io.IOException;
import java.util.List;
import java.util.Vector;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author sinem
 */
@WebServlet(name="VerifyUser", urlPatterns={"/VerifyUser"})
public class VerifyUser extends HttpServlet {
    @EJB
    private NewsFacade newsFacade;
    @EJB
    private UsersFacade usersFacade;


    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

         String url=request.getQueryString();
         String error = url.substring(url.indexOf('=')+1);

        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        if(userName==null ||userName.equals("") || password==null || password.equals("")){
            response.sendRedirect("jsps/Login.jsp?Error=5");
            return;
        }

        Users u=usersFacade.find(usersFacade.getIdByUser(userName));
        if(u==null)
        {
             response.sendRedirect("jsps/Login.jsp?Error=1");
             return;
        }
        boolean activated =u.isActive();
        int type = u.getType();

        if(usersFacade.validateUser(userName, password))
        {
            if(!activated) {
                response.sendRedirect("jsps/Login.jsp?Error=3");
                return;
            }

            HttpSession session = request.getSession(true);
            session.invalidate();
            session = request.getSession(true);
            session.setAttribute("userName", userName);
            session.setAttribute("type", type);
            session.setAttribute("activated", true);
            session.setAttribute("location", u.getLocation());

            ejb.News newsArray[]=new ejb.News[3];


            if(u.getLocation()==null || u.getLocation().equals("-"))
            {

                List<ejb.News> news=newsFacade.findAll();
                int size=news.size();
                for(int i=0;i<(size < 3 ? size : 3);i++)
                {
                    System.out.println("newssiez: "+(size-1-i));
                    newsArray[i]=(ejb.News)newsFacade.find(news.get(size-1-i).getId());
                }
                session.setAttribute("news", newsArray);
            }
            else
            {
                    System.out.println(u.getLocation());
                    String keywords[]={u.getLocation()};
                    Vector<Long> news= newsFacade.getByKeyword(keywords);
                    int newssize=news.size();
                    for(int i=0;i<(newssize<3 ? newssize : 3);i++)
                    {
                        newsArray[i]=(ejb.News)newsFacade.find(news.get(newssize-1-i));
                    }
                    session.setAttribute("news", newsArray);
            }
System.out.println("8");
            response.sendRedirect("ListNews");
        }
        else if(error.equals("1")) {
            response.sendRedirect("jsps/Login.jsp?Error=1");
        }
        else {
           response.sendRedirect("jsps/Login.jsp?Error=2");
        }

        //response.setContentType("text/html;charset=UTF-8");
        //        PrintWriter out = response.getWriter();
        try {
             //TODO output your page here
            /*
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ShowMessage</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ShowMessage at " + request.getContextPath () + "</h1>");
            out.println(type+"<br />");
            out.println("<a href=\"ListNews\">Return Home</a>");
            out.println("</body>");
            out.println("</html>");*/

        } finally {
            //out.close();
        }



        }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    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
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
