#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include "oak.h"

oak_fire *fire_create(char *in) {
  /* create a fire to be timed from the string "time" */

  oak_fire *out;
  struct tm *nexttime;
  time_t now;
  int foo, hour, min;

  out=malloc(sizeof(oak_fire));
  if (!strcasecmp(in, "now")) {
    out->interval=10;
    out->next=time(NULL)+out->interval;
  }  else if (in[0]=='*') {
    foo=atoi(in+1);
    if (!strcasecmp(in+strlen(in)-1, "h") ||
	!strcasecmp(in+strlen(in)-2, "hr")) {
      foo=foo*3600;
    } else if (!strcasecmp(in+strlen(in)-1, "m") ||
	       !strcasecmp(in+strlen(in)-3, "min")) {
      foo=foo*60;
    }
    out->interval=foo;
    out->next=time(NULL)+out->interval;
  } else {
    
    /* it must be 00:00 format, we'll do am/pm some other day */
    out->interval=3600*24;
    hour=atoi(in);
    min=atoi(strchr(in, ':')+1);
    now=time(NULL);
    nexttime=localtime(&now);
    nexttime->tm_sec=0;
    nexttime->tm_min=min;
    nexttime->tm_hour=hour;
    /* leave tm_mday as today for now */
    out->next=mktime(nexttime);
    /* if the time has passed today go for tomorrow */
    if (out->next < time(NULL)) {
      out->next = out->next + (3600 * 24);
    }
  }
  
  if (DEBUG) {
    printf("DEBUG: fire next is at %s\n", ctime(&(out->next)));
    printf("DEBUG: fire interval is %i\n", (int) out->interval);
  }

  return(out);
}

int fire_is_time(oak_fire *f) {
  /* if it's not time to fire return 0.
     if it is time to fire return 1 and update fire->next
       for subsequent calls ot fire_is_time
  */

  if (f->next < time(NULL)) {
    /* figure out f->next.  Keep incrementing by f->interval until
       it's a time that hasn't occured yet */
    while (1) {
      f->next+=f->interval;
      if (f->next > time(NULL)) break;
    }
    return(1);
  }

  return(0);
}
