/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set sw=2 sts=2 et cin: */
/*
 * This file is part of the MUSE Instrument Pipeline
 * Copyright (C) 2016 European Southern Observatory
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

#define _DEFAULT_SOURCE
#define _BSD_SOURCE /* get mkdtemp() from stdlib.h */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

#include <muse.h>

#define DIR_TEMPLATE "/tmp/muse_table_test_XXXXXX"
#define OBJECT_STRING "Test muse_table"

/*----------------------------------------------------------------------------*/
/**
  @brief    Test program to check that all the functions from the muse_table
            module work correctly.

  This program explicitely tests
    muse_table_new
    muse_table_delete
    muse_table_save
    muse_table_load
 */
/*----------------------------------------------------------------------------*/
int main(int argc, char **argv)
{
  UNUSED_ARGUMENTS(argc, argv);
  cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_DEBUG);

  /* create a muse_table */
  muse_table *table = muse_table_new();
  /* now the muse_table should be non-NULL and the components should be NULL */
  cpl_test_nonnull(table);
  cpl_test_null(table->table);
  cpl_test_null(table->header);

  /* test freeing when the muse_table doesn't actually contain an table */
  cpl_errorstate state = cpl_errorstate_get();
  muse_table_delete(table);
  table = NULL;
  cpl_test(cpl_errorstate_is_equal(state));

  /* now create a muse_table with content and add a header */
  int nrow = 5;
  table = muse_table_new();
  table->table = cpl_table_new(nrow);
  cpl_test_nonnull(table->table);
  cpl_table_new_column(table->table, "TEST", CPL_TYPE_INT);
  cpl_table_fill_column_window_int(table->table, "TEST", 0, 5, 3);
  cpl_table_set_int(table->table, "TEST", 3, -3); /* different 4th entry */
  table->header = cpl_propertylist_new();
  cpl_test_nonnull(table->header);
  cpl_propertylist_append_string(table->header, "OBJECT", OBJECT_STRING);

  /* save the table to a (temporary) file */
  char dirtemplate[FILENAME_MAX] = DIR_TEMPLATE;
  char *dir = mkdtemp(dirtemplate);
  char *file = cpl_sprintf("%s/%s", dir, "muse_table.fits");
#if 0
  cpl_table_dump(table->table, 0, nrow, stdout);
  fflush(stdout);
#endif
  cpl_error_code rc = muse_table_save(table, (const char *)file);
  cpl_test_zero(rc);
  cpl_msg_info(__func__, "Written to \"%s\"", file);
  struct stat sb;
  cpl_test_zero(stat(file, &sb));
  /* the file written should be a normal file with size greater than zero... */
  cpl_test(S_ISREG(sb.st_mode) && sb.st_size > 0);
  /* ... and contain one extension, the one with the table */
  cpl_test(cpl_fits_count_extensions(file) == 1);

  /* try to load the file again that we just saved */
  muse_table *table2 = muse_table_load(file, 0); /* generic, no IFU */
  cpl_test_nonnull(table2);
  cpl_test_nonnull(table2->header);
  const char *object = cpl_propertylist_get_string(table2->header, "OBJECT");
  cpl_test_zero(strncmp(object, OBJECT_STRING, strlen(OBJECT_STRING) + 1));
  /* Test that the tables are identical, with the same number of rows */
  cpl_test_zero(cpl_table_compare_structure(table->table, table2->table));
  cpl_test_eq(nrow, cpl_table_get_nrow(table2->table));
  int i;
  for (i = 0; i < nrow; i++) {
    cpl_test_eq(cpl_table_get_int(table->table, "TEST", i, NULL),
                cpl_table_get_int(table2->table, "TEST", i, NULL));
  }

  /* test freeing when the muse_table is filled */
  state = cpl_errorstate_get();
  muse_table_delete(table2);
  cpl_test(cpl_errorstate_is_equal(state));

  /* modify original table, and save in an extension with an IFU EXTNAME */
  cpl_table_name_column(table->table, "TEST", "IFU");
  cpl_table_fill_column_window_int(table->table, "IFU", 0, 2, 12);
  nrow = 6; /* add another row, that will have an invalid entry! */
  cpl_table_set_size(table->table, nrow);
  cpl_propertylist *hext = cpl_propertylist_new();
  cpl_propertylist_append_string(hext, "EXTNAME", "CHAN10");
#if 0
  cpl_table_dump(table->table, 0, nrow, stdout);
  fflush(stdout);
#endif
  cpl_table_save(table->table, NULL, hext, file, CPL_IO_EXTEND);
  cpl_propertylist_delete(hext);
  muse_table *table10 = muse_table_load(file, 10), /* right IFU */
             *table11 = muse_table_load(file, 11); /* wrong IFU */
  cpl_test_nonnull(table10);
  cpl_test_nonnull(table10->table);
  cpl_test_nonnull(table10->header);
  cpl_test(cpl_propertylist_has(table10->header, "EXTNAME"));
  object = cpl_propertylist_get_string(table10->header, "OBJECT");
  cpl_test_zero(strncmp(object, OBJECT_STRING, strlen(OBJECT_STRING) + 1));
  /* Test that the tables are identical, with the same number of rows */
  cpl_test_zero(cpl_table_compare_structure(table->table, table10->table));
  cpl_test_eq(nrow, cpl_table_get_nrow(table10->table));
  for (i = 0; i < nrow; i++) {
    cpl_test_eq(cpl_table_get_int(table->table, "IFU", i, NULL),
                cpl_table_get_int(table10->table, "IFU", i, NULL));
  }
  muse_table_delete(table10);
  /* loading of table11 should still have succeeded, with first table */
  cpl_test_nonnull(table11);
  cpl_test_nonnull(table11->table);
  cpl_test_nonnull(table11->header);
  // XXX the following leaks with CPL 7.0
  //cpl_test(cpl_table_compare_structure(table->table, table11->table) == 1);
  cpl_array *cols = cpl_table_get_column_names(table11->table);
  cpl_test_eq_string(cpl_array_get_string(cols, 0), "TEST");
  cpl_array_delete(cols);
  cpl_test(!cpl_propertylist_has(table11->header, "EXTNAME"));
  object = cpl_propertylist_get_string(table11->header, "OBJECT");
  cpl_test_zero(strncmp(object, OBJECT_STRING, strlen(OBJECT_STRING) + 1));
  muse_table_delete(table11);

  /* test failure cases of muse_table_load() */
  state = cpl_errorstate_get();
  table2 = muse_table_load(NULL, 0);
  cpl_test(!cpl_errorstate_is_equal(state) &&
           cpl_error_get_code() == CPL_ERROR_NULL_INPUT);
  cpl_test_null(table2);
  cpl_errorstate_set(state);
  table2 = muse_table_load("blabla", 0); /* non-existing file */
  cpl_test(!cpl_errorstate_is_equal(state) &&
           cpl_error_get_code() == CPL_ERROR_FILE_NOT_FOUND);
  cpl_test_null(table2);
  cpl_errorstate_set(state);

  /* now we can remove the file again, use the return values to check that *
   * nothing else went wrong with the file in the meantime                 */
  cpl_test_zero(remove(file));
  cpl_test_zero(rmdir(dir));
  cpl_free(file);
  muse_table_delete(table);

  return cpl_test_end(0);
}
