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

package web;


import ejb.Users;
import ejb.UsersFacade;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;

import javax.ejb.EJB;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author sinem
 */
@WebServlet(name="Register", urlPatterns={"/Register"})
public class Register extends HttpServlet {
    @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 {
boolean tmp=false ;

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

        String userName=request.getParameter("userName").toString();
        String password2=request.getParameter("password").toString();
        String email = request.getParameter("email").toString();
        String location = request.getParameter("location").toString();
        String name= request.getParameter("name").toString();
        String surname= request.getParameter("surname").toString();
        String phone= request.getParameter("phone").toString();
        String birthday=request.getParameter("birthday").toString();
        String preferred=request.getParameter("preferred").toString();


        boolean whiteSpace = userName.matches("\\s");
        boolean nonAlpha = userName.matches("\\W");


        if(userName.equals("") || password2.equals("") || email.equals("") || name.equals("")|| surname.equals("")||phone.equals("")) {
            response.sendRedirect("jsps/Register.jsp?Error=2");
            return;}
            else if(whiteSpace || nonAlpha) {
                response.sendRedirect("jsps/Register.jsp?Error=5");
                return;
            }
            else if(usersFacade.userExists(userName)) {
             response.sendRedirect("jsps/Register.jsp?Error=1");
            return;}
            else if(!email.contains("@")) {
             response.sendRedirect("jsps/Register.jsp?Error=3");
            return;}
            else {
                    Users u = new Users();
                    u.setActive(false);
                    u.setEmail(email);
                    u.setPassword(password2);
                    u.setType(2);
                    u.setUserName(userName);
                    u.setName(name);
                    u.setSurname(surname);
                    if(location.equals(""))
                        u.setLocation(location);
                    if(!birthday.equals(""))
                        u.setBirthday(birthday);
                    if(!preferred.equals(""))
                        u.setPreferredCity(preferred);
                    usersFacade.create(u);
                    

                    //------------------------------------------------------
String file = request.getRequestURI();
if (request.getQueryString() != null) {
   file += '?' + request.getQueryString();
}
URL reconstructedURL = new URL(request.getScheme(),
                               request.getServerName(),
                               request.getServerPort(),
                               file);

  String url=reconstructedURL.toString().substring(0,reconstructedURL.toString().lastIndexOf("/")+1)+
          "Activation?userName="+userName;
        final String err = "/error.jsp";
        final String succ = "jsps/Register.jsp?Error=4";

        String from ="trenbilgisistemi@gmail.com";
        String to = email;
        String subject = "Tren Bilgi Sistemi Aktivasyon Maili";
        String message = url;
        String login = "trenbilgisistemi@gmail.com";
        String password = "bugbusters491";

        try {
            Properties props = new Properties();
            props.setProperty("mail.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");

            Authenticator auth = new SMTPAuthenticator(login, password);

            Session session = Session.getInstance(props, auth);

            MimeMessage msg = new MimeMessage(session);
            msg.setText(message);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            Transport.send(msg);
            response.sendRedirect("jsps/Register.jsp?Error=4");

        } catch (AuthenticationFailedException ex) {
            request.setAttribute("ErrorMessage", "Authentication failed");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);

        } catch (AddressException ex) {
            request.setAttribute("ErrorMessage", "Wrong email address");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);

        } catch (MessagingException ex) {
            request.setAttribute("ErrorMessage", ex.getMessage());

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);
        }
          //  RequestDispatcher dispatcher = request.getRequestDispatcher(succ);
          //  dispatcher.forward(request, response);





                    //-----------------------------------------------------

            }

 
    } 

    // <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>

        private class SMTPAuthenticator extends Authenticator {

        private PasswordAuthentication authentication;

        public SMTPAuthenticator(String login, String password) {
            authentication = new PasswordAuthentication(login, password);
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }


}
