#include <WScom.h>
#include <WSCfunctionList.h>
#include <WSCbase.h>
//----------------------------------------------------------
//Function for the event procedure
//----------------------------------------------------------
#include <WSDappDev.h>
#include <WSCconductor.h>
#include <WSCmessageDialog.h>
#include <WSClocaleSet.h>
#include <newwin000.h>

WSCstring ipaddr("127.0.0.1");
WSCstring bind_ipaddr("");
WSCstring broadcast_ipaddr("255.255.255.255");

void initop(WSCbase* object){
  WSCstring* envstr = WSGFreadTextFile("$(HOME)/.wsagentrc");
  if (envstr != NULL){
    ipaddr = envstr->gets();
    broadcast_ipaddr = envstr->gets();
    ipaddr.delHeadSpace();
    ipaddr.delTailSpace();
    ipaddr.delLineFeed();
    broadcast_ipaddr.delHeadSpace();
    broadcast_ipaddr.delTailSpace();
    broadcast_ipaddr.delLineFeed();
    delete envstr;
  }

  //do something...
  if (WSGIappDev()->getArgc() > 1){
    char** ptr = WSGIappDev()->getArgv();
    bind_ipaddr.setString(ptr[1]);
  }

  WSGIconductor()->setAddr(bind_ipaddr.getString());
  newvudp_000->setBindAddr(bind_ipaddr.getString());

  if (WSGIappDev()->getArgc() > 2){
    char** ptr = WSGIappDev()->getArgv();
    broadcast_ipaddr.setString(ptr[2]);
  }
  newvudp_000->setProperty(WSNip,broadcast_ipaddr.getString());

  WSGIconductor()->setPort(WS_DEFAULT_AGENT_PORT);
  WSGIconductor()->startDispatch();
  newvudp_000->setProperty(WSNport,WS_DEFAULT_AGENT_UDP_PORT);
  newvudp_000->setProperty(WSNrunning,True);
//printf("initop...\n");

  newvifi_011->setProperty(WSNlabelString,ipaddr);
  newvifi_012->setProperty(WSNlabelString,broadcast_ipaddr);

  WSCuchar buffer[256];
  WSCushort port = WS_DEFAULT_AGENT_UDP_PORT;
  buffer[0] = 'w';
  buffer[1] = 's';
  buffer[2] = 'a';
  buffer[3] = 'U'; //UPDATE: requests new instance data.
  buffer[4] = port & 0xff;
  buffer[5] = port >> 8;
  strncpy((char*)&buffer[6],ipaddr.getString(),26);
  buffer[31] = 0;
  strncpy((char*)&buffer[32],"",48);
  buffer[79] = 0;
  strncpy((char*)&buffer[80],"",64);
  buffer[143] = 0;
  strncpy((char*)&buffer[144],"",64);
  buffer[207] = 0;
  long ret = newvudp_000->write(buffer,256);
//printf("ret=%d\n",ret);
  if (ret != 256){
    char buffer[256];
    newvudp_000->getErrorMsg(buffer,256);
    char buffer2[1024];
    sprintf(buffer2,"wsagent: error in initializing.\nudp_send:%d %s\nCan not broad cast...",ret,buffer);
    long locale = WSGIappLocaleSet()->getSystemLocaleEncoding();
    WSCstring msg(buffer2,locale);
    WSGIappLocaleSet()->setDefaultEncoding(locale);
    WSGIappMessageDialog()->setProperty(WSNlabelString,msg);
    WSGIappMessageDialog()->setProperty(WSNwidth,640);
    WSGIappMessageDialog()->setProperty(WSNheight,145);
    WSGIappMessageDialog()->setProperty(WSNdefaultPosition,1);
    WSGIappMessageDialog()->popup();
  }
}
static WSCfunctionRegister  op("initop",(void*)initop);
