import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;

public class autobusesCliente{
    
     public static void main(String args[]){
        new autobusesCliente();
    }
    
    autobusesCliente(){
        // La ventana que muestra el programa
        JFrame ventana=new JFrame("Estacion de autobuses de SORIA");
        ventana.setSize(600,500);
        ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // El panel que contiene los elementos
        JPanel panel=new JPanel();
        JTextArea entradas=new JTextArea(12,1);
        JTextArea salidas=new JTextArea(12,1);
        Font fuente=new Font("Dialog", Font.BOLD, 24);
        entradas.setFont(fuente);
        salidas.setFont(fuente);
        panel.add(entradas);
        panel.add(salidas);
        ventana.add(panel);
        ventana.setVisible(true);
        
        try{
            // Se une al grupo
            InetAddress grupo=InetAddress.getByName("224.0.0.1");
            MulticastSocket socket=new MulticastSocket(6789);
            socket.joinGroup(grupo);
            // Lleno un Vector con los datos recibidos
            while(true){
                ArrayList datos=llena(socket);
                // Imprimo las entradas
                imprime(datos,"E",entradas);
                imprime(datos,"S",salidas);
            }
   
            // socket.leaveGroup(grupo);
        }catch(Exception e){
            System.out.println("Error en el programa principal");
        }
    }
    
    void imprime(ArrayList datos,String tipo,JTextArea ta){
        String texto="";
        if(tipo.equals("E")) texto="ENTRADAS\r\n=======================\r\n";
        else texto="SALIDAS\r\n=======================\r\n";
        // Obtengo la hora actual
        Calendar calendario = Calendar.getInstance();
        String ahora =calendario.get(Calendar.HOUR_OF_DAY)+":"+calendario.get(Calendar.MINUTE);
        // Recorro linea a linea el ArrayList y creo otro ArrayList con los registros posteriores y anteriores
        ArrayList<String> horasDespues=new ArrayList<String>();
        ArrayList<String> horasAntes=new ArrayList<String>(); 
        for(int i=0;i<datos.size()-1;i++){
            String linea=(String)datos.get(i);
            String cachos[]=linea.split(";");
            if (cachos[1].equals(tipo)){
                if(cachos[0].compareTo(ahora)>0)
                    horasDespues.add(cachos[0]+"\t"+cachos[2]);
                else
                    horasAntes.add(cachos[0]+"\t"+cachos[2]);
            }
        }  
        // Ordeno por las horas
        Collections.sort(horasAntes);
        Collections.sort(horasDespues);
        // Imprimo en el JTextArea que me han dado
        for(int i=0;i<horasDespues.size();i++) texto+=horasDespues.get(i)+"\r\n";
        texto+="------------------------------------\r\n";
        for(int i=0;i<horasAntes.size();i++) texto+=horasAntes.get(i)+"\r\n";
        ta.setText(texto);    
    }
    
    ArrayList llena(MulticastSocket socket){
        ArrayList<String> respuesta=new ArrayList<String>();
        try{
            // Variables para recibir paquetes de datos
            byte[] bufer=new byte[1000];
            String linea="";
            // Si la linea recibida es FIN quiere decir que ha recibido todo el fichero
            while(!linea.equals("FIN")){
                DatagramPacket mensajeEntrada=new DatagramPacket(bufer,bufer.length);
                socket.receive(mensajeEntrada);
                linea=new String(mensajeEntrada.getData(),0,mensajeEntrada.getLength());
                // meto la linea en el Vector
                respuesta.add(linea);
            }
            
        }catch(Exception e){
            System.out.println("Error en el metodo llena()");
        }    
        return respuesta;
    }

}
