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

package web;

import ejb.SeyirDefteri;
import ejb.SeyirDefteriFacade;
import ejb.Trains;
import ejb.TrainsFacade;
import ejb.Users;
import ejb.UsersFacade;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

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 zwergnase
 */
@WebServlet(name="Emergency", urlPatterns={"/Emergency"})
public class Emergency extends HttpServlet {
    @EJB
    static private TrainsFacade trainsFacade;
    @EJB
    static private SeyirDefteriFacade seyirDefteriFacade;
    @EJB
    static private UsersFacade usersFacade;
    
    Long trainId;

    Emergency(String trainId)
    {
        this.trainId=Long.parseLong(trainId);
    }
 
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        //response.setContentType("text/html;charset=UTF-8");
        //PrintWriter out = response.getWriter();
       
        List<SeyirDefteri> allsefers=null;
        try{
            allsefers=seyirDefteriFacade.findAll();
        }catch(Exception e){
            e.printStackTrace();
        }
        if(allsefers==null)
        {
            System.out.println("BOŞ LANNNN");
        }
     else{
        int seferSize=allsefers.size();
        Vector<Long> usersToMail=new Vector<Long>();

        for(int i=0;i<seferSize;i++)
        {
            SeyirDefteri s=allsefers.get(i);

            if(s.getTrainId().contains(trainId))
            {
                Long userId=s.getUserId();
                if(!usersToMail.contains(userId))
                    usersToMail.addElement(userId);
                System.out.println("user!!!!:"+userId);
            }
        }


        int usersize=usersToMail.size();
        for(int i=0;i<usersize;i++)
        {
                Users u=usersFacade.find(usersToMail.get(i));
                Trains t=trainsFacade.find(trainId);

                final String err = "";
                final String succ = "";

                String from ="trenbilgisistemi@gmail.com";
                String to = u.getEmail();
                String subject = "Tren Bilgi Sistemi Aktivasyon Maili";
                String message = trainId + " nolu "+ t.getName() + "treni aldığımız verilere göre devrilmiştir." +
                        "Kayıtlarımızda bu trene ait biletiniz olduğu saptanmıştır. Lütfen bileti iptal edip yeni bir hat" +
                        " üzerinden gitmeyi deneyiniz.";
                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);
                   

                } catch (Exception ex) {
                    ex.printStackTrace();

                } 
                }
         }
    }

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