#include <assert.h>
#include <stdlib.h>

#include "field.h"
#include "mesh.h"
#include "mpicomm.h"

void int_field_init(int_field_t *field, const conf_t *configuration, const mesh_t *mesh)
{
   field->configuration = configuration;
   field->mesh = mesh;

   field->data = malloc(mesh->extended_local_domain.volume * sizeof(int));
}

void int_field_free(int_field_t *field)
{
   free(field->data);
   field->data = NULL;
}

void int_field_set_constant(int_field_t *field, int value)
{
   int i, n;
   int *data;

   n = field->mesh->extended_local_domain.volume;
   data = field->data;

   for(i = 0; i < n; i++) data[i] = value;
}

int int_field_check_value(const int_field_t *field, const box_t *domain, int expected_value)
{
   const mesh_t* mesh = field->mesh;
   const int *c = domain->coords;
   const int *e = domain->extents;
   const int *data = field->data;
   int x, y, z, idx;;

   for(z = c[Z]; z < c[Z] + e[Z]; z++) {
      for(y = c[Y]; y < c[Y] + e[Y]; y++) {
         for(x = c[X]; x < c[X] + e[X]; x++) {
            idx = mesh_idx(mesh, x, y, z);
            if(data[idx] != expected_value) return 0;
         }
      }
   }
   return 1;
}

void int_field_halo_exchange(int_field_t *field)
{
   int mode = field->configuration->transfer_mode;
   switch(mode) {
      case SPARSE_COLLECTIVE:
            mpi_halo_exchange_int_sparse_collective(field); break;
      case COLLECTIVE:
            mpi_halo_exchange_int_collective(field); break;
      case P2P_DEFAULT:
            mpi_halo_exchange_int_p2p_default(field); break;
      case P2P_SYNCHRONOUS:
            mpi_halo_exchange_int_p2p_synchronous(field); break;
      case P2P_READY:
            mpi_halo_exchange_int_p2p_ready(field); break;
   }
}
