#include <stdio.h>

#include "boinc_db.h"
#include "ap_db.h"
#include "ap_result.h"
#include "assimilate_handler.h"

int assimilate_handler(
    WORKUNIT& wu, vector<RESULT>& results, RESULT& canonical_result
) {
  //APWORKUNIT apwu;
  AP_SIGNAL s;
  struct ap_result *r;
  int n;
  char path[256];
  int i;
  static int first_time=1;

  printf("assimilating WU %s\n", wu.name);
  if (wu.canonical_resultid) {
    printf("canonical result:\n%s", canonical_result.xml_doc_out);
  } else {
    printf("no canonical result\n");
  }
  if (wu.error_mask&WU_ERROR_COULDNT_SEND_RESULT) {
    printf("Error: couldn't send a result\n");
  }
  if (wu.error_mask&WU_ERROR_TOO_MANY_ERROR_RESULTS) {
    printf("Error: too many error results\n");
  }
  if (wu.error_mask&WU_ERROR_TOO_MANY_RESULTS) {
    printf("Error: too many total results\n");
  }

  // Read canonical result file
  get_output_file_path(canonical_result, path);
  n = ap_read_malloc(path, &r);

  if (n <= 0) {
    printf("Error reading canonical result.\n");
    return(-1);
  }

  if (first_time)  {
    if (ap_db_open(AP_DB_NAME, "") == -1) {
      ap_db_print_error("ap_db_open");
      return(-2);
    }
    first_time = 0;
  }


  // insert results into AP "signal" table
  for (i=0; i<n; i++) {
    // set up SIGNAL structure
    s.id = 0;
    s.apwu_id = wu.opaque;
    s.fft_num = r[i].fft_num;
    s.peak_bin = r[i].peak_bin;
    s.peak_power = r[i].peak_power;
    s.scale = r[i].scale;
    s.dm = r[i].dm;
    s.period = r[i].period;

    // Need to deal with time series

    // Insert into db
    if (db_signal_new(&s)) {
      ap_db_print_error("db_signal_new");
      return(-2);
    }
  }

  // modify ap "workunit" table
  //   - make note of any errors
  //   - flag wu as "done"
  // db_apworkunit_update(&apwu);

  return(0);

}
