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

package web;

import ejb.BestPaths;
import ejb.BestPathsFacade;
import ejb.Cities;
import ejb.CitiesFacade;
import ejb.Trains;
import ejb.TrainsFacade;
import java.io.IOException;

import java.util.List;
import java.util.ListIterator;
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="PathFinder", urlPatterns={"/PathFinder"})
public class PathFinder extends HttpServlet {
    @EJB
    private TrainsFacade trainsFacade;
    @EJB
    private BestPathsFacade bestPathsFacade;
    @EJB
    private CitiesFacade citiesFacade;


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

         //TODO BOŞ GELİRSE DEAFULT VALUE SET EDİLMELİ
         HttpSession session=request.getSession(true);
         String from=request.getParameter("from");
         String to=request.getParameter("to");
         String travelDate=request.getParameter("depdate");
         // we need these to filter
         String depTime=request.getParameter("deptime");
         String arrTime=request.getParameter("arrtime");
         int cost=Integer.parseInt(request.getParameter("cost"));
         int change=Integer.parseInt(request.getParameter("change"));
         int wait=Integer.parseInt(request.getParameter("wait"));
         

         // get the ids of the cities
         Long sourceId=citiesFacade.findByName(from);
         Long destId=citiesFacade.findByName(to);
         // TODO: send redirect to another page
         if(sourceId.equals(-1L))
         {
             System.out.println("Source city is undefined");
             return;
         }
         else if(destId.equals(-1L))
         {
             System.out.println("Destination city is undefined");
             return;
         }

         // take the inputs from best paths and cities table
         List<BestPaths> bpList=bestPathsFacade.findAll();
         List<Cities> ctList=citiesFacade.findAll();
         List<Trains> trList=trainsFacade.findAll();

         // find available paths
         OptimumPath op=new OptimumPath(sourceId, destId,bpList,ctList);

         // filter and find all proper ways to go
         PathFilter pf=new PathFilter(wait,cost,change,depTime,arrTime,op.availablePaths,bpList,trList);
         pf.findAllWays();
         setTheNamesOfSubpaths(pf, ctList);

        // burada artık filterlama başlıyor.
         /* first eliminate all train hours out of the interval
          * for each available path
          *     take the first successive pairs in this path     
          *     choose all trains and put them into a stack with their dep and arrival times
          *         while(1)
          *         take the next city pair
          *         for all trains between next city pair look at the same trains.(if exists) take the first
          *         same train.dont look at the others. calculate cost change vs.
          *         if no similar train: max saat içindeki tüm trenleri ekle pathin içine cost ve aktarmaları ilave et
          *         eğer önceki pathlerde aynı tren varsa alma. bir daha.aynı trenlerin sadece ilkini alabilirsin.
          *         farklı trenlerin de ilk uyanına bakacaksın max. bu şekilde farklı yollar oluşacak. 
          */

         session.setAttribute("ways", pf.getAvailableWays());
         session.setAttribute("depdate", travelDate);
         session.setAttribute("from", from);
         session.setAttribute("to", to);
         session.setAttribute("deptime", depTime);
         session.setAttribute("arrtime", arrTime);
         session.setAttribute("cost", cost);
         session.setAttribute("change", change);
         session.setAttribute("wait", wait);
         
        


         /*
         session.setAttribute("numOfPaths",op.availablePaths.size());
         int avsize=op.availablePaths.size();

         // filter available paths

        for(int i=0;i<avsize;i++)
        {
           String city="";
           Vector cityNodes=op.availablePaths.get(i).nodes;
           int nodesize=cityNodes.size();
           for(int j=0;j<nodesize;j++)
           {
               city=city.concat(((City)op.connections.get(cityNodes.get(j))).name+";");
           }
        city=city.substring(0,city.length()-1);
        //System.out.println(city);
        session.setAttribute("cities"+Integer.toString(i), city);
        }
          *
          */

         response.sendRedirect("jsps/PassengerHome.jsp");
         return;


    }

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

       //wee need this in passengerhome.jsp
   void setTheNamesOfSubpaths(PathFilter pf,List<Cities> cities)
   {
       Vector<Way> ways=pf.getAvailableWays();
       int numberOfWays=ways.size();
       for(int i=0;i<numberOfWays;i++)
       {
           Vector<subpath> subs=ways.get(i).pathSoFar;
           int numOfSubs=subs.size();
           for(int j=0;j<numOfSubs;j++)
           {
               subpath s=subs.get(j);
               ListIterator<Cities> li=cities.listIterator();
               while(li.hasNext())
               {
                    Cities c=li.next();
                    if(c.getId().equals(s.cityId))
                    {
                        s.cityName=c.getName();
                        break;
                    }
               }
           }
       }
   }// end of function
}




//--------------------------PATH FILTER-----------------------------class pthFilter

