package org.postgresql.util;

import java.sql.SQLException;
import java.net.MulticastSocket;
import java.net.InetAddress;
import java.net.DatagramPacket;


public class MCUtil {

  private MulticastSocket s;
  private InetAddress group;
  private int port;
  private String ipMC;
  private int sizeBuffer = 2048;

  public int getSizeBuffer () {
    return sizeBuffer;
  }

  public void setSizeBuffer (int size) {
    sizeBuffer = size;
  }

  public MCUtil (String ip, int p) throws SQLException {
    port = p;
    ipMC = ip;
    try {
      group = InetAddress.getByName(ipMC);
      s = new MulticastSocket(port);
      //System.out.print("Multicast Server listening on ip " + ipMC + " port  ");
      //System.out.println(s.getLocalPort());
      s.joinGroup(group);
    } catch (Exception e) {
      throw new SQLException ("Error to init multicast socket");
    }
  }


  public void sendDiscovery () throws SQLException {
    byte [] buf = new byte[4];
    buf[0] = 9;
    buf[1] = 0;
    buf[2] = 0;
    buf[3] = 0;
    try {
      DatagramPacket data = new DatagramPacket(buf, buf.length,
                                               group, port);
      //System.out.println("Discovery " + new String(buf));
      s.send(data);
    } catch (Exception e) {
      throw new SQLException ("Error sending datas");
    }
  }


  public void sendMC (int msg) throws SQLException {
    try {
      String m = Integer.toString(msg);
      System.out.println("   mensaje : " + msg);
      sendMC(m);

    } catch (Exception e) {
      throw new SQLException ("Error sending datas");
    }

  }

  public void sendMC (String msg) throws SQLException {
    byte buf[] = msg.getBytes();
    try {
      DatagramPacket data = new DatagramPacket(buf, buf.length,
                                               group, port);
      //System.out.println("   mensaje : " + msg);
      s.send(data);
    } catch (Exception e) {
      throw new SQLException ("Error sending datas");
    }

  }

  public String recvMC (int timeout) throws SQLException, java.net.SocketTimeoutException {
    byte[] buf;
    try {
      s.setSoTimeout(timeout /*timeout JSalas*/);
      buf = new byte[sizeBuffer];
      
      for (int i=0; i < buf.length; i++){
      	buf[0]=0;
      }
      
      DatagramPacket recv = new DatagramPacket(buf, buf.length);      
      s.receive(recv);
      String data = new String(buf);
      //System.out.println("Receive MC" + data.toString());

    } catch (java.net.SocketTimeoutException e) {
      throw new java.net.SocketTimeoutException ("Timeout exception");
    }
    catch (Exception e) {
      throw new PSQLException ("Error receving datas");
    }
    return new String (buf);
  }


  public void closeMCSocket () throws SQLException {
    try {
      s.leaveGroup(group);
      s.close();
    } catch (Exception e) {
      throw new PSQLException ("Error closing multicast socket");
    }
  }
};

