// Thread per l'aggiornamento delle richieste pendenti sul Master 

import java.net.*;
import java.io.IOException;
import java.util.Hashtable;

class UpdateQueryMaster extends Thread {
  private DatagramSocket soc;
  private DatagramPacket ackPac;
    
  public UpdateQueryMaster() {
    super("UpdateQueryMaster");
    try { System.out.print("Init UpdateQueryMaster Thread ... ");
          soc=new DatagramSocket(ConstantsS.queryPort+1);
          byte[] b="".getBytes();
          ackPac=new DatagramPacket(b,b.length,InetAddress.getByName(ConstantsS.masterIP),ConstantsS.masterPort+1);
          ConstantsS.queryList=new Hashtable();
          System.out.println("fatto.");
            
    } catch(SocketException ex) {
   	    System.out.println("Slave$UpdateQueryMaster: "+ex.toString());
        System.exit(ConstantsS.queryPort+1);
   	  }
   	  catch(SecurityException ex) {
   	    System.out.println("Slave$UpdateQueryMaster: "+ex.toString());
   	    System.exit(ConstantsS.queryPort+1);
   	  }
      catch(UnknownHostException ex) {
   	    System.out.println("Slave$UpdateQueryMaster: "+ex.toString());
   	    System.exit(ConstantsS.queryPort+1);
   	  }
  }
      
  public void run() {
         
    while (true)
      try { byte[] inb=new byte[Constants.maxLungAmbito+10]; // max lunghezza comandi set/unset
            DatagramPacket inPac=new DatagramPacket(inb,inb.length);
            soc.receive(inPac);
            soc.send(ackPac); // invia l'ack
            String cmd=(new String(inPac.getData())).trim();
            System.out.println("Slave$UpdateQueryMaster: cmd from "+(inPac.getAddress()).getHostAddress()+" "+inPac.getPort()+" "+cmd);
            int pos=cmd.indexOf(' ');
            if ((cmd.substring(0,pos)).equals("set"))
                  { int index_start=-1;
                  	for (int j=0;j<4;j++) index_start=cmd.indexOf('\n',++index_start);
                  	ConstantsS.queryList.put(cmd.substring(pos+1,index_start),new QueryListElem(cmd.substring(index_start+1,cmd.length())));
                  }
             else if ((cmd.substring(0,pos)).equals("setv"))
                        { int vivi_start=-1;
                  	      for (int j=0;j<4;j++) vivi_start=cmd.indexOf('\n',++vivi_start);
                        	QueryListElem el=(QueryListElem)ConstantsS.queryList.get(cmd.substring(pos+1,vivi_start));
                        	if (el!=null)
                           el.setV(cmd.substring(vivi_start+1,cmd.length())); 
                        }
                   else if ((cmd.substring(0,pos)).equals("unset"))
             	           ConstantsS.queryList.remove(cmd.substring(pos+1,cmd.length()));
      
      } catch(IOException ex) {
    	    System.out.println("Slave$UpdateQueryMaster: "+ex.toString());
    	  }
  }		
} // fine UpdateQueryMaster