#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdint.h>
#include <syslog.h>
#include <stdarg.h>

#include "../../status.h"
#include "../../feeder.h"


void (*feederLog) (int priority, const char *fmt, ...);

int
setLog (void *func)
{
  feederLog = func;
  return 0;
}

int
init (void *param)
{
  param = param;

  return 0;
}

static uint16_t packet;

unsigned int
process(void *lib_data, int socket, unsigned char *data,
        unsigned int length, unsigned long long int *id, time_t * tm,
        double *result_array, uint64_t * sensors, unsigned int *type)
{
  unsigned int ret = 0;
  char cmd[16];
  uint64_t lid;

  char *tok_next;
  int i;
  char *tokens[20];
  double lat, lon, alt;
  time_t ts;

  if ((data == NULL) || (length == 0))
    return 0;

  feederLog (LOG_DEBUG, "genloc_kk: data %s\n", data);

  memcpy (cmd, data, 4);
  cmd[4] = 0;
  tok_next = (char *) data + 5;
  i = 0;
  while (tokens[i++] = strsep (&tok_next, ","), tok_next != NULL);

//sscanf((char *)data, "%s '%lld',%ld", cmd, &lid, &packet);

  lid = atoll (tokens[0] + 1);
  packet = atol (tokens[1]);
  ts = atol(tokens[2]);

  feederLog (LOG_DEBUG,
             "genloc_kk: data from %lld, cmd %s, packet number %ld\n",
             (unsigned long long int) lid, cmd, (unsigned long int) packet);

  if (lid != 0)
    {
      if (strcmp (cmd, "FT2P") == 0)
        {
          if (atoi(tokens[3]) > 0)	/* validity flag */
          {
            lat = atof (tokens[4]);
            lon = atof (tokens[5]);
            alt = atof (tokens[6]);
            feederLog (LOG_DEBUG, "genloc_kk: lat %f, lon %f, alt %f\n", lat,
                     lon, alt);

            result_array[0] = lat;
            result_array[1] = lon;
            result_array[2] = alt;
            sensors[0] = sensors[1] = sensors[2] = 0x10;
            *type = VALUES_TYPE_POS;
            *id = lid;
            *tm = ts;
 
            ret = 3;
          }
          else
          {
    	     feederLog (LOG_WARNING, "genloc_kk: Invalid position\n");
          }
        }
    }
  else
    {
      feederLog (LOG_WARNING, "genloc_kk: Bad unit id\n");
    }

  return ret;
}

int reply(void *lib_data, int socket, unsigned char *data)
{
  sprintf ((char *) data, "OK,%ld", (unsigned long int) packet);

  feederLog (LOG_DEBUG, "genloc_kk: replying %s\n", data);

  return strlen ((char *) data);
}

int close(void *lib_data, int socket)
{
  feederLog (LOG_DEBUG, "genloc_kk: socket closed\n");

  return 0;
}
