//=============================================================================
/**
 *  @file UserDefinedFunction.cpp
 *
 *   Sonus Networks, Inc.
 *
 *   All Rights Reserved
 *   Confidential and Proprietary.
 *
 *  @author Howard Finer - Westford <hfiner@sonusnet.com>
 *
 *  @brief Code to be loaded into MySQL as a user defined function
 *
 */
//=============================================================================
#include <iostream>
#include <mysql/mysql.h>
using namespace std;

extern "C" 
{
int dbchange_init(UDF_INIT *initid, UDF_ARGS *args, char *message);
void dbchange_deinit(UDF_INIT *initid);
long long dbchange(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error);
};


int dbchange_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
  int retVal(0);
  bool error(false);
  if( args->arg_count > 2 )
    {
      error = true;
    }
  else
    {
      for( int i=0; i < args->arg_count && !error; i++ )
        {
          if( args->arg_type[i] != STRING_RESULT )
            {
              error = true;
            }
        }
    }

  if( error )
  {
    strcpy(message,"Wrong arguments to dbchange function");
    retVal = 1;
  }

  // max size string we will return
  initid->maybe_null=0;		/* The result may NOT be null */
  initid->decimals=0;		/* We want 0 decimals in the result */
  initid->max_length=2;     /* 1 digits + . + 0 decimals -- 0 or 1 */

  return retVal;
}

void dbchange_deinit(UDF_INIT* /*initid*/)
{
  // nothing to do upon unloading
}

// use the system call to call an SAF-aware app to send a message to
// the dbproxy service. Pass both the name of the table and the queue name.
// Queue name is passed so we have a way to change it on the fly by
// changing the trigger.
long long dbchange(UDF_INIT * /*initid*/,
                   UDF_ARGS *args, char * /*is_null*/, char* /*error*/)
{
  string name(args->args[0],args->lengths[0]);
  string queueName(args->args[1],args->lengths[1]);
  string command = "DbChangeNotifier -t " + name + " -q " + queueName;

  // put the timestamp into the log so we can track all changes
  // be sure to remove the newline so it is all on one line
  // (newline is replaced with a space)
  time_t currTime = time(NULL);
  string timeStampStr = ctime(&currTime);
  timeStampStr.replace(timeStampStr.length()-1,1,1,' ');

  // the following gets written to the mysql log file. track all changes
  cout << timeStampStr
       << " Database change notification sent for table "
       <<  name << " to queue with base name " << queueName << endl;

  system(command.c_str());
  return 0;
}

