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

package web;


import ejb.Cities;
import ejb.CitiesFacade;
import ejb.EscalatedToFacade;
import ejb.Knowledge;
import ejb.KnowledgeFacade;
import ejb.Lines;
import ejb.LinesFacade;
import ejb.Schedule;
import ejb.SeferFacade;

import ejb.SessionManagerBean;
import ejb.Trains;
import ejb.TrainsFacade;
import ejb.Users;
import ejb.UsersFacade;

import ejb.ScheduleFacade;
import ejb.Sefer;

import java.io.IOException;

import java.io.PrintWriter;
import java.sql.Date;
import java.sql.Time;


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;


//0 admin
//1 mak
//2 normal kullanıcı
@WebServlet(name="ListNews", urlPatterns={"/ListNews"})
public class ListNews extends HttpServlet {
    @EJB
    private CitiesFacade citiesFacade;
    @EJB
    private LinesFacade linesFacade;
    @EJB
    private SeferFacade seferFacade;
    @EJB
    private KnowledgeFacade knowledgeFacade;
    @EJB
    private EscalatedToFacade escalatedToFacade;
    @EJB
    private ScheduleFacade scheduleFacade;
    @EJB
    private TrainsFacade trainsFacade;
    @EJB
    private UsersFacade usersFacade;
    @EJB
    private SessionManagerBean sessionManagerBean;



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

        //getMessages();
        HttpSession session=request.getSession(true);
        Long creationTime = session.getCreationTime();
        String userName=session.getAttribute("userName").toString();
        int type=Integer.parseInt(session.getAttribute("type").toString());
        boolean isRegistered=(session.getAttribute("userName")==null ||session.getAttribute("activated")==null||
                session.getAttribute("activated").toString().equals("false")) ? false : true;


        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();


        if(!isRegistered) {
            response.sendRedirect("jsps/Login.jsp");
            return;
            //session.setAttribute("type", "4");
        }
        else
        {


         if(type==1){

    out.println("<html>"+
    "<head>"+
        "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"+
        "<link href=\"design/css/machome.css\" type=\"text/css\" rel=\"stylesheet\" />"+
        "<title>Makinist Görev Tablosu</title>"+
    "</head>"+
"<body>"+
"<p id='logout'><a href=\"Logout\">Logout!</a></p>"+
"<div id=\"genel\">"+

"<div id=\"baslik\">"+
"<img src=\"design/Pictures/homesmall.jpg\" width=\"70px\" height=\"70px\"/><font id=\"basliktext\"> Ana Sayfa</font>"+
"</div>"+


"<table id=\"anatablo\">"+
"<tr><td>"+
"<div id=\"links\">"+
"<p>"+
"<a href='http://www.ceng.metu.edu.tr/~e1502103' target=\"_blank\">"+
    "<input type=\"button\" value=\"Tren Takip Sistemi\" id=\"linkbutton\" /></a>"+

"</p>"+
"</div>"+
"</td>"+

"<td >"+
"<div id=\"secondcell\">"+
"<p>"+
"<b>Ana Sayfaya Hoşgeldiniz! </b><br />"+
"<form name=\"ListScheduleMac\" action=\"ListNews\" method=\"POST\">"+
"<input type=\"text\" size=\"20\" height=\"20\" name=\"date\"> tarihli görev tablonuza bu sayfadan ulaşabilirsiniz."+
"<input type=\"submit\"  size=\"20\" height=\"20\" value=\"Listele!\"/>" +
"</form>"+
"</p>"+
"</table>");



            long uid=usersFacade.getIdByUser(userName);
            System.out.println("uid:"+uid);
            Users Mac=usersFacade.find(uid);
            System.out.println("uname: "+Mac.getName());
            //tarih şartı eklenecek

            String dateOfSchedule=request.getParameter("date");

            if(dateOfSchedule==null)
            {
                out.println("<p id=\"tarihsec\">Lütfen bir tarih seçiniz!</p></td>");

            }
            else // tarih var
            {
                        String[] splitted=dateOfSchedule.split("/");
                        java.util.Date utilDate=new java.util.Date(Integer.parseInt(splitted[2])-1900,
                                Integer.parseInt(splitted[1])-1,
                                Integer.parseInt(splitted[0])
                                );
                        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

                List<Long> schedulesForMac = scheduleFacade.scheduleForMach2(Mac.getId(),sqlDate);// tarihli sorgu

                  if(schedulesForMac==null)
                    {
                       out.println("<p id=\"tarihsec\">Bu gün için size atanan bir görev bulunmamaktadır!</p>");
                    }//print you dont have any schedule

            else
            {
                out.println("<table id=\"results\">");
                int size=schedulesForMac.size();
                int numofschedule=0;
                out.println("<tr bgcolor=\"Navy\">"+
                "<th><font color=\"White\"> Sefer Num.</font></th>"+
                "<th><font color=\"White\"> Tren Adı</font></th>"+
                "<th><font color=\"White\"> Hat Adı</font></th>"+
                "<th><font color=\"White\"> Kalkış Yeri</font></th>"+
                "<th><font color=\"White\"> Kalkış Saati</font></th>"+
                "<th><font color=\"White\"> Varış Yeri</font></th>"+
                "<th><font color=\"White\"> Varış Saati</font></th>"+
                "</tr>");

               for(int i=0;i<size;i++)
               {
                   Schedule Sch=scheduleFacade.find(schedulesForMac.get(i));
                   Sefer S=seferFacade.find(Sch.getSeferId());
                   Date D=Sch.getScheduleDate();
                   Trains T=trainsFacade.find(S.getTrainId());
                   Lines L=linesFacade.find(S.getLineId());
                   Vector<Time> times=S.getTimes();
                   Vector<Long> cities=L.getCities();
                   int citysize=cities.size();
                   for(int j=0,k=0;j<citysize-1;j++,k++)
                   {
                       System.out.println(cities.get(j));
                        out.println("<tr>");
                        out.println("<td>"+S.getId()+"</td>");
                        out.println("<td>"+T.getName()+"</td>");
                        out.println("<td>"+L.getName()+"</td>");
                        out.println("<td>"+((Cities)citiesFacade.find(cities.get(j))).getName()+"</td>");
                        out.println("<td>"+times.get(k++)+"</td>");
                        out.println("<td>"+((Cities)citiesFacade.find(cities.get(j+1))).getName()+"</td>");
                        out.println("<td>"+times.get(k)+"</td>");
                        out.println("</tr>");
                        numofschedule++;
                   }



               }
                out.println("</table>");

            }//else bitti
      }// end of else


            out.println("<p><a href=\"Logout\">Logout!</a></p>");
         }//machinist

         else if(type==2)//normal kullanıcı
         {

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

         }
         else if(type==0)
         {
    out.println("<head>"+
        "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"+
        "<link href=\"design/css/machome.css\" type=\"text/css\" rel=\"stylesheet\" />"+
        "<title>Admin Sayfası</title>"+
    "</head>"+
"<body>"+
"<div id=\"genel\">"+

"<div id=\"baslik\">"+
"<img src=\"design/Pictures/homesmall.jpg\" width=\"70px\" height=\"70px\"/><font id=\"basliktext\"> Ana Sayfa</font>"+
"</div>"+


"<table id=\"anatablo\">"+
"<tr><td>"+
"<div id=\"links\">"+
"<p>"+
"<input type=\"button\" value=\"Haber Ekle\"  id=\"linkbutton\" ONCLICK=\"window.location.href='News'\"/>"+
"</p><p>"+
"<input type=\"submit\" value=\"Görev Ekle\" id=\"linkbutton\" ONCLICK=\"window.location.href='AddSchedule'\"/>"+
"</p><p>"+
"<input type=\"button\" value=\"Sorun Giderme\"  id=\"linkbutton\" ONCLICK=\"window.location.href='jsps/KnowledgeDB.jsp'\"/>"+
"</p><p>"+
"<input type=\"button\" value=\"Kişisel Bilgiler\"  id=\"linkbutton\" ONCLICK=\"window.location.href='findperson'\"  />"+
"</p>"+
"</div>"+
"</td>"+

"<td >"+
"<div id=\"secondcell\">"+
"<p>"+
"<b>Ana Sayfaya Hoşgeldiniz! </b><br />"+
"Size verilen görevler aşağıda listelenmiştir."+
"</p>"+


"</table>");



    Long uid=usersFacade.getIdByUser(userName);
    Users u=usersFacade.find(uid);
    List<Long> problems=escalatedToFacade.getProblemByUser(uid);
    /*
    out.println("<table id=\"problemstable\">"); //thler gelecek
            out.println("<tr>");
            out.println("<th>No.</th><th>Başlık</th><th>İçerik</th><th>Durum</th></tr>");
    if(problems.size()==0)
    {
        out.println("</table>");
    }
    else
    {
        for(int i=0;i<problems.size();i++){
            Knowledge p=knowledgeFacade.find(problems.get(i));
            out.println("<tr>");
            out.println("<td>"+p.getId()+"</td>");
            out.println("<td>"+p.getTitle()+"</td>");
            if(p.getDescription().length()>100)
                out.println("<td>"+p.getDescription().substring(0,100)+"...</td>");
            else
                out.println("<td>"+p.getDescription()+"</td>");
            out.println("<td>"+p.getStatus()+"</td>");
            out.println("</tr>");
        }
        out.println("</table>");

    }
           */
out.println("<p id=\"logout\"><a href=\"Logout\">Logout!</a></p>");



         }//else

        }//else




    }

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