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

package web;

import ejb.SeyirDefteriFacade;
import ejb.UsersFacade;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Time;
import java.sql.Date;
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 zwergnase
 */
@WebServlet(name="SaveSefer", urlPatterns={"/SaveSefer"})
public class SaveSefer extends HttpServlet {
    @EJB
    private SeyirDefteriFacade seyirDefteriFacade;
    @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 {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        //Burda ways ve sefer kayıt edilecek database tablosuna sonra ok mesajı gösterilecek!!
        //ways parse edilecek. her subpath de ayrıştırılıp vektörlere dolacak. sonra insert. Göster derse. gösterilecek.
        //acton fire nasıl yapılır.
        //eğer 0 sa handle et geri gönder.
try{
         HttpSession session=request.getSession(true);
         String userName=session.getAttribute("userName").toString();
         Long userId=usersFacade.getIdByUser(userName);
         Vector<Way> ways=(Vector<Way>)session.getAttribute("ways");
         String wayIndices[] = request.getParameterValues("wayIndices");
         String sourceCity=session.getAttribute("from").toString();
         String depDate=session.getAttribute("depdate").toString();

         int size=wayIndices.length;
         System.out.println("size "+size);
         System.out.println("sourcecity: "+sourceCity);
         System.out.println("depDate "+depDate);
         String splitted[]=depDate.split("\\.");


         Date travelDate=new Date(Integer.parseInt(splitted[2])-1900,Integer.parseInt(splitted[1])-1,Integer.parseInt(splitted[0]));

         
         for(int i=0;i<size;i++)        //for each way
         {


             Way wayToSave=ways.get(Integer.parseInt(wayIndices[i]));


             Vector<String> places=new Vector<String>();
             Vector<Time> arrivalTimes=new Vector<Time>();
             Vector<Time> departureTimes=new Vector<Time>();
             Vector<Float> cost=new Vector<Float>();
             //Vector<Long> cityIds=new Vector<Long>();
             Vector<Long> trainIds=new Vector<Long>();

             places.addElement(sourceCity);
            
             ejb.SeyirDefteri seferTosave=new ejb.SeyirDefteri();
             
             Vector<subpath> subs=wayToSave.pathSoFar;
             int subSize=subs.size();
             seferTosave.setChange(wayToSave.changesSoFar);
             seferTosave.setIsTicket(0);
             seferTosave.setUserId(userId);
             seferTosave.setTravelDate(travelDate);
             seferTosave.setTravelLength(wayToSave.totalDistance);


             System.out.println("Distance "+wayToSave.totalDistance);
             for(int j=0;j<subSize;j++)             //for each subpath
             {

                 subpath subPath=subs.get(j);
                 subPath.printSubpath();

                 places.addElement(subPath.getCityName());
                 arrivalTimes.addElement(subPath.getArrTime());
                 departureTimes.addElement(subPath.getDepTime());
                 cost.addElement(subPath.getPartialCost());
                 trainIds.addElement(subPath.trainId);
                 //cityIds.addElement(subPath.cityId);------------------_> do we need this?
             }
             seferTosave.setArrivalTime(arrivalTimes);
             seferTosave.setDepartureTime(departureTimes);
             seferTosave.setPlaces(places);
             seferTosave.setCost(cost);
             seferTosave.setTrainId(trainIds);
             seyirDefteriFacade.create(seferTosave);

         }

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

        try {
            
           response.setContentType("text/html;charset=UTF-8");

            /* TODO output your page here*/

            out.println("<html>");
            out.println("<head>");
            out.println("<link href=\"design/css/logout.css\" type=\"text/css\" rel=\"stylesheet\" />");
            out.println("<title>Sefer Kaydetme</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<table id=\"success\"><tr>");
            out.println("<td rowspan=\"2\" ><img src=\"design/Pictures/info.png\" /></td>");
            out.println("<td align=\"center\" id=\"rightcell\"> Seçtiğiniz seferler başarıyla kaydedilmiştir! </td></tr>");
            out.println("<tr><td align=\"center\" id=\"rightcell\">Kayıtlı seferleri görmek için <a href=\"SeyirDefteri\">tıklayınız!</a> </td></tr></table>");
            out.println("<a href=\"jsps/PassengerHome.jsp\"><img id=\"home\" src=\"design/Pictures/home.png\"></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>

}
