/* Birthdate.c -- A couple of functions for manipulating the birthdate.
   Used by makeusers, edituser and birthdays. */

#include <config.h>
#include "recedit.h"
#include <general.h>

#if !defined (NULL)
#define NULL 0
#endif

#if !defined savestring
#define savestring(x) (char *)strcpy ((char *)xmalloc (1 + strlen (x)), x)
#endif

/* The names of fields potentially containing the users birthdate. */
static char *birthfields[] = {
  "Birth Date",
  "Birthday",
  "D.O.B.",
  "Geburtstag",
  "Date of Birth",
  (char *)NULL
};

/* Return the name of the field containing the birthdate, or
   NULL if none. */
char *
birthdate_field_name (fields)
     FIELD_DESC **fields;
{
  register int i;
  FIELD_DESC *temp;

  for (i = 0; birthfields[i]; i++)
    {
      temp = re_find_field (fields, birthfields[i]);

      if (temp)
	return (birthfields[i]);
    }

  return ((char *)NULL);
}

/* Find the field containing the birthdate in FIELDS, and return it.
   Return NULL if the field cannot be found. */
FIELD_DESC *
birthdate_field (fields)
     FIELD_DESC **fields;
{
  register int i;
  FIELD_DESC *result = (FIELD_DESC *)NULL;

  for (i = 0; birthfields[i]; i++)
    {
      result = re_find_field (fields, birthfields[i]);

      if (result)
	break;
    }

  return (result);
}

/* Return a pointer to a DATE which is the decoded birthddate
   found in BFIELD.  We can decode DATE and CHAR fields. */
DATE *
decode_birthdate (bfield)
     FIELD_DESC *bfield;
{
  DATE *date = (DATE *)NULL;

  switch (bfield->type)
    {
    case Date:
      {
	date = (DATE *)xmalloc (sizeof (DATE));
	bcopy (bfield->data.date, date, sizeof (DATE));
      }
      break;

    case Char:
      {
	int day, month, year;

	sscanf (bfield->data.chardata, "%d/%d/%d", &month, &day, &year);
	date = (DATE *)xmalloc (sizeof (DATE));

	date->day = day;
	date->month = month;
	date->year = year;
      }
      break;
    }
    
  return (date);
}

/* Set the birth date field of FIELDS to DATE.  DATE must be passed as a
   pointer to a DATE structure.  Returns 1 if FIELDS contains a birthdate
   field, and was set, else 0. */
int
set_birthdate_field (fields, date)
     FIELD_DESC **fields;
     DATE *date;
{
  char *name;
  FIELD_DESC *bfield;

  bfield = birthdate_field (fields);

  if (bfield)
    switch (bfield->type)
      {
      case Date:
	bfield->data.date.month = date->month;
	bfield->data.date.day = date->day;
	bfield->data.date.year = date->year;
	return (1);
	break;

      case Char:
	{
	  char temp[100];

	  sprintf (temp, "%d/%d/%d", date->month, date->day, date->year);
	  bfield->data.chardata = savestring (temp);
	  return (1);
	}
      }
  return (0);
}


      

  
