/*
 * 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.Lines;
import ejb.LinesFacade;
import ejb.Sefer;
import ejb.SeferFacade;
import ejb.Trains;
import ejb.TrainsFacade;
import ejb.Users;
import ejb.UsersFacade;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Time;
import java.util.TreeMap;
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;

/**
 *
 * @author zwergnase
 */
@WebServlet(name="LoadFromDB", urlPatterns={"/LoadFromDB"})
public class LoadFromDB extends HttpServlet {
    @EJB
    private SeferFacade seferFacade;
    @EJB
    private LinesFacade linesFacade;
    @EJB
    private UsersFacade usersFacade;
    @EJB
    private TrainsFacade trainsFacade;
    @EJB
    private CitiesFacade citiesFacade;
    @EJB
    private BestPathsFacade bestPathsFacade;



    /**
     * 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 {
        
        String str=null;
        FileReader fr=null;
        BufferedReader inputStream=null;
        try
        {
        /* TO LOAD TRANIS UNCOMMENT THIS.  CHECK IF THEY ARE CORREC IF NOT PLEASE REPORT IT!*/
        //Load trains

/*
            String path=request.getRequestURL().substring(0,request.getRequestURL().lastIndexOf("/"));
            fr=new FileReader("/home/zwergnase/Desktop/bitirmeIcin/database/Trains.txt");
            inputStream = new BufferedReader(fr);
            str=inputStream.readLine(); // first line is dummy for trains.txt
            while((str=inputStream.readLine())!=null)
            {
                // split the string
                String splitted[]=str.split(";");
                // load all columns (id included)
                Trains T=new Trains();
                T.setId(Long.parseLong(splitted[0]));
                T.setName(splitted[1]);
                T.setCosts(Float.parseFloat(splitted[2]));
                T.setTrainType(splitted[3].charAt(0));
                trainsFacade.create(T);
            }

           // close all streams
            inputStream.close();
            fr.close();
*/

//------------------------------------------------
            //Load Cities
  /*
            fr=new FileReader("/home/zwergnase/Desktop/bitirmeIcin/database/Cities.txt");
            inputStream=new BufferedReader(fr);
            str=inputStream.readLine(); // first line is dummy for cities.txt
            while((str=inputStream.readLine())!=null)
            {
                 // split the string
                String splitted[]=str.split(";");
                // load all columns (id included)
                Cities C=new Cities();
                C.setId(Long.parseLong(splitted[0]));
                C.setName(splitted[1]);
                C.setX_coor(Float.parseFloat(splitted[2]));
                C.setY_coor(Float.parseFloat(splitted[3]));
                citiesFacade.create(C);
            }
            // close all streams
            inputStream.close();
            fr.close();
*/
//----------------------
            //TO LOAD BEST PATH UNCOMMENT THIS. PLEASE LOAD ONE BY ONE
                /*
            fr=new FileReader("/home/zwergnase/Desktop/bitirmeIcin/database/BestPath.txt");
            inputStream=new BufferedReader(fr);
            str=inputStream.readLine(); // first line is dummy for BestPath.txt
            while((str=inputStream.readLine())!=null)
            {
                
                // split the string
                String splitted[]=str.split(";");
                //System.out.println("size: "+splitted.length);
                Float distance=Float.parseFloat(splitted[5]);
                // begin to form best path
                BestPaths bp=new BestPaths();
                bp.setDeparturePlace(Long.parseLong(splitted[0]));
                bp.setArrivalPlace(Long.parseLong(splitted[1]));
                bp.setDistance(distance);
                //System.out.println(splitted[0]+" "+splitted[1]+" "+splitted[2]+ " "+splitted[4]);
                // now create the TreeMap
                TreeMap arrivalForBp=new TreeMap<Long,Vector<Time> >();
                TreeMap departureForBp=new TreeMap<Long,Vector<Time> >();


                String[] trains=splitted[2].split(","); //split trainIds
                int numberOfTrains=trains.length;     //get its length
                String[] dtimes=splitted[3].split("-");  //split times
                String[] atimes=splitted[4].split("-");
                //System.out.println("trains "+trains[0]+" "+trains[1]);

                // for each train y
                for(int i=0;i<numberOfTrains;i++)
                {
                    //System.out.println("train ıd "+Long.parseLong(trains[i]));
                    Long trainId=Long.parseLong(trains[i]);

                    //vector of times
                    Vector<Time> Arrivals=new Vector<Time>();
                    Vector<Time> Departures=new Vector<Time>();

                    String[] depTimes= dtimes[i].split(",");//bir tren için tüm kalkış zamanları
                    String[] arrTimes= atimes[i].split(",");//bir tren için tüm varış zamanları
                    int numberOfDepartures=depTimes.length;  // kaç kalkış var
                    for(int j=0;j< numberOfDepartures;j++)
                    {
                        // cant we parse the data
                        String[] dhm=depTimes[j].split(":");
                        // get departure time
                        Time deptime=new Time(Integer.parseInt(dhm[0]),Integer.parseInt(dhm[1]),0);
                        
                        String[] ahm=arrTimes[j].split(":");
                        Time arrtime=new Time(Integer.parseInt(ahm[0]),Integer.parseInt(ahm[1]),0);
                        


                        // add them to vectors
                        Arrivals.addElement(arrtime);
                        Departures.addElement(deptime);
                    }

                    //put them to Treemap
                    departureForBp.put(trainId,Departures);
                    arrivalForBp.put(trainId,Arrivals);
                }// end of number of trains train i

                bp.setArrivalTimes(arrivalForBp);
                bp.setDepartureTimes(departureForBp);
                bestPathsFacade.create(bp);

            }// end of while
            // close all streams
            inputStream.close();
            fr.close();*/

                  //Load some Machinists
            fr=new FileReader("/home/zwergnase/Desktop/bitirmeIcin/database/Machinists.txt");
            inputStream = new BufferedReader(fr);
            str=inputStream.readLine(); // first line is dummy for machnists.txt
            while((str=inputStream.readLine())!=null)
            {
                // split the string
                String splitted[]=str.split(";");
                // load all columns (id included)
                Users U=new Users();
                U.setType(1);
                U.setActive(true);
                U.setUserName(splitted[0]);
                U.setPassword(splitted[1]);
                U.setName(splitted[2]);
                U.setSurname(splitted[3]);
                U.setBirthday(splitted[4]);
                U.setEmail(splitted[5]);
                U.setTelephone(splitted[6]);
                U.setLocation(splitted[7]);
                usersFacade.create(U);
            }
/*
            //Load some Lines
            fr=new FileReader("/home/zwergnase/Desktop/bitirmeIcin/database/Lines.txt");
            inputStream = new BufferedReader(fr);
            str=inputStream.readLine(); // first line is dummy for machnists.txt
            while((str=inputStream.readLine())!=null)
            {
                // split the string
                String splitted[]=str.split(";");
                String splittedCities[]=splitted[0].split(",");
                Vector<Long> cityIds=new Vector<Long>();
                int size=splittedCities.length;
                for(int i=0;i<size;i++)
                    cityIds.addElement(Long.parseLong(splittedCities[i]));
                Lines L=new Lines();
                L.setCities(cityIds);
                L.setName(splitted[1]);
                linesFacade.create(L);             
            }
*//*

            fr=new FileReader("/home/zwergnase/Desktop/bitirmeIcin/database/Sefer.txt");
            inputStream = new BufferedReader(fr);
            str=inputStream.readLine(); // first line is dummy for sefer.txt
            while((str=inputStream.readLine())!=null)
            {
                // split the string
                String splitted[]=str.split(";");
                String splittedTimes[]=splitted[0].split(",");

                Vector<Time> Times=new Vector<Time>();
                int size=splittedTimes.length;
                for(int i=0;i<size;i++)
                {
                    String splittedPart[]=splittedTimes[i].split(":");
                    Times.addElement(new Time(Integer.parseInt(splittedPart[0]),
                            Integer.parseInt(splittedPart[1]),0));
                }
               Sefer S=new Sefer();
               S.setTimes(Times);
               S.setTrainId(Long.parseLong(splitted[1]));
               S.setLineId(Long.parseLong(splitted[2]));
               seferFacade.create(S);
               
            }
*/

    }

    catch(Exception e)
    {
        System.err.println("Error while parsing input files");
        e.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>

}


// to delete


                        //int newMin=(Integer.parseInt(hm[1])+minutes)%60;
                        //int newHour=((Integer.parseInt(hm[1])+minutes)/60+Integer.parseInt(hm[0])+hours)%24;
                        // calculate arrival time
                        //Time arrtime=new Time(newHour,newMin,0);
                        //System.out.println("arrtime "+arrtime.toString());
                        //System.out.println("depttime "+deptime.toString());

                    //Trains T= trainsFacade.find(trainId);
                    //if(T==null)
                        //System.out.print("boş lan buu!!");
                    //int velocity=T.getSpeed();
                    // calculate the length of the travel to find arrival times
                   // int hours=distance.intValue()/velocity;
                    //int minutes=new Float(((distance%velocity)/velocity)*60).intValue();
                    //System.out.println("velocity "+velocity+" distance "+ distance+" hours "+hours+" minutes "+ minutes);