/* Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <b.h>

struct b_sync_data_t
{
  b_io_t *io;
  b_uint64 max_cache;
};

static b_int64 b_sync_write (unsigned char *what, b_uint64 size, void *dummy);
static b_error_t b_sync_cache_empty (b_t * data, b_io_t * io);
static b_error_t b_sync_instances_cache (b_t * data, b_cache_t * cache,
					 b_type_t type, char add);

/**
 * b_sync:
 * @data: The pointer to a b_t data struct.
 * @returns: The error code.
 * 
 * Syncs the storage. You shouldn't use this function because B storage syncs
 * the data automaticly.
 **/
b_error_t
b_sync (b_t * data)
{
  b_error_t error;

  B_LOG1 ("b_sync: %p", data);

  if (!data)
    return B_ERROR_DATA;

  /* A different function for the triples: */
  if ((error = b_sync_tcache (data)) != B_OK)
    return error;

  return B_OK;
}

/* This function syncs a single list: */
b_error_t
b_sync_cache (b_t * data, b_io_t * io, unsigned char *hash,
	      unsigned char *what, b_uint64 len)
{
  b_map_t m, map;
  b_uint64 pointer;
  int cmp;

  B_LOG5 ("b_sync_cache: %p %p %p %p %d", data, io, hash, what, (int) len);

  memset (&map, 0, sizeof (b_map_t));
  b_hash_copy (map.hash, hash);
  map.len = len;

  pointer = b_io_seek (io, sizeof (b_uint64), SEEK_SET);

  /* The b-tree starts with a empty elements, so I can't read it doesn't
   * exist: */
  if (b_io_read (io, &m, sizeof (m)) <= 0)
    {
      b_error_t err;

      /* This write must be protected: */
      b_journaling_new (data, io, B_JOURNALING_CACHE_EMPTY);

      if ((err = b_sync_cache_empty (data, io)) != B_OK)
	{
	  b_journaling_destroy (data);
	  return err;
	}

      b_journaling_destroy (data);

      /* Recursion: */
      return b_sync_cache (data, io, hash, what, len);
    }

  pointer = b_io_seek (io, sizeof (b_uint64), SEEK_SET);

  while (1)
    {
      /* Try to read but only if it is not the first node 
       * (I have read it already 10 lines before): */
      if (pointer != sizeof (b_uint64) && b_io_read (io, &m, sizeof (m)) <= 0)
	return B_ERROR_INTERNAL;

      cmp = b_hash_compare (map.hash, m.hash);

      if (cmp <= 0)
	{
	  if (m.left)
	    {
	      pointer = b_io_seek (io, m.left, SEEK_SET);
	      continue;
	    }
	  else
	    {
	      b_uint64 end;
	      map.parent = pointer;

	      /* Write the new element: */
	      end = b_io_seek (io, 0, SEEK_END);

	      b_journaling_new (data, io, B_JOURNALING_END_WRITE, end);

	      if (b_io_write (io, &map, sizeof (b_map_t), data->max_cache) <=
		  0)
		{
		  b_journaling_destroy (data);
		  return B_ERROR_POSIX;
		}

	      if (map.len
		  && b_io_write (io, what, map.len, data->max_cache) <= 0)
		{
		  b_journaling_destroy (data);
		  return B_ERROR_POSIX;
		}

	      /* Set the left node to the parent: */
	      b_io_seek (io, pointer, SEEK_SET);
	      if (b_io_read (io, &m, sizeof (m)) <= 0)
		{
		  b_journaling_destroy (data);
		  return B_ERROR_INTERNAL;
		}

	      b_journaling_new (data, io, B_JOURNALING_WRITE, pointer,
				sizeof (b_map_t), &m);

	      m.left = end;

	      b_io_seek (io, pointer, SEEK_SET);

	      if (b_io_write (io, &m, sizeof (b_map_t), data->max_cache) <= 0)
		{
		  b_journaling_destroy (data);
		  return B_ERROR_POSIX;
		}

	      b_journaling_destroy (data);
	      return B_OK;
	    }
	}

      else
	{
	  if (m.right)
	    {
	      pointer = b_io_seek (io, m.right, SEEK_SET);
	      continue;
	    }
	  else
	    {
	      b_uint64 end;
	      map.parent = pointer;

	      /* Write the new element: */
	      end = b_io_seek (io, 0, SEEK_END);

	      b_journaling_new (data, io, B_JOURNALING_END_WRITE, end);

	      if (b_io_write (io, &map, sizeof (b_map_t), data->max_cache) <=
		  0)
		{
		  b_journaling_destroy (data);
		  return B_ERROR_POSIX;
		}

	      if (map.len
		  && b_io_write (io, what, map.len, data->max_cache) <= 0)
		{
		  b_journaling_destroy (data);
		  return B_ERROR_POSIX;
		}

	      /* Set the right node to the parent: */
	      b_io_seek (io, pointer, SEEK_SET);
	      if (b_io_read (io, &m, sizeof (m)) <= 0)
		{
		  b_journaling_destroy (data);
		  return B_ERROR_INTERNAL;
		}

	      b_journaling_new (data, io, B_JOURNALING_WRITE, pointer,
				sizeof (b_map_t), &m);

	      m.right = end;

	      b_io_seek (io, pointer, SEEK_SET);

	      if (b_io_write (io, &m, sizeof (b_map_t), data->max_cache) <= 0)
		{
		  b_journaling_destroy (data);
		  return B_ERROR_POSIX;
		}

	      b_journaling_destroy (data);
	      return B_OK;
	    }
	}
    }

  return B_OK;
}

/* Empty cache: */
static b_error_t
b_sync_cache_empty (b_t * data, b_io_t * io)
{
  b_map_t map;
  b_error_t err;
  b_string_t *str;

  memset (&map, 0, sizeof (b_map_t));
  map.len = 1;

  if ((err = b_hash_new (data, (unsigned char *) "", 0, map.hash)) != B_OK)
    return err;

  b_io_seek (io, sizeof (b_uint64), SEEK_SET);

  if ((err = b_string_new (&str)) != B_OK)
    return err;

  if ((err =
       b_string_add (str, (unsigned char *) &map, sizeof (b_map_t))) != B_OK)
    {
      b_string_destroy (str, NULL);
      return err;
    }

  if ((err = b_string_add (str, (unsigned char *) "", 1)) != B_OK)
    {
      b_string_destroy (str, NULL);
      return err;
    }

  if (b_io_write (io, str->string, str->size, data->max_cache) <= 0)
    {
      b_string_destroy (str, NULL);
      return B_ERROR_POSIX;
    }

  return b_string_destroy (str, NULL);
}

/* This function syncs a single triple list: */
b_error_t
b_sync_tcache (b_t * data)
{
  b_uint64 pointer;
  b_error_t error;
  b_tcache_t *cache;
  unsigned char empty[B_TRIPLE_SIZE];
  struct b_sync_data_t write_data;

  B_LOG1 ("b_sync_tcache: %p", data);

  if (!data->triples_cache)
    return B_OK;

  /* Empty element: */
  memset (empty, 0, sizeof (empty));

  /* Until we have cache: */
  cache = data->triples_cache;
  while (cache)
    {
      int numb, i, j, b;
      b_tmap_t tmap;
      b_tmap_item_t tmap_item;
      b_tcache_t *caches[B_TMAP_NUMB];
      char caches_free[B_TMAP_NUMB];
      char tosync = 0;
      char fromtempty = 0;

      memset (caches, 0, sizeof (caches));
      memset (caches_free, 0, sizeof (caches_free));

      /* FIXME: This code doesn't work yet: */
      if (1 || b_tempty_get (data, &tmap, &pointer))
	{
	  /* Creating a empty map: */
	  memset (&tmap, 0, sizeof (tmap));
	  pointer = b_io_seek (data->triples_io, 0, SEEK_END);
	}
      else
	fromtempty = 1;

      /* Until the map is not full: */
      for (numb = 0; cache && numb < B_TMAP_NUMB; cache = cache->next, numb++)
	{
	  /* If the cache element is already storage, I restart researc a
	   * new element: */
	  if (cache->tmap_pointer)
	    {
	      numb -= 1;
	      continue;
	    }

	  /* Search a empty space in the current map: */
	  while (tmap.map[numb] == 1 && numb < B_TMAP_NUMB)
	    numb++;

	  if (numb >= B_TMAP_NUMB)
	    break;

	  tmap.map[numb] = 1;

	  /* Set the new values in the cache struct: */
	  cache->tmap_pointer = pointer;
	  cache->tmap_index = numb;

	  caches[numb] = cache;
	  tosync = 1;

	  if (fromtempty)
	    {
	      b_tcache_copy (caches[numb], &caches[numb]);
	      caches_free[numb] = 1;
	    }

#define B_SYNC_GET( x , l , t ) \
  if (b_io_read (data->triples_io, &tmap_item, \
		 sizeof (b_tmap_item_t)) <= 0) \
    { \
      b_tcache_destroy_single (NULL, NULL, caches[i]); \
      return B_ERROR_INTERNAL; \
    } \
  \
  if (tmap_item.pointer) \
    { \
      if ((error = b_get_type_pointer (data, t, tmap_item.pointer, \
	                               &caches[value]->x)) \
          != B_OK) \
	{ \
          b_tcache_destroy_single (NULL, NULL, caches[value]); \
	  return error; \
	} \
      \
      if (!caches[value]->x) \
	{ \
          b_tcache_destroy_single (NULL, NULL, caches[value]); \
	  return B_ERROR_INTERNAL; \
	} \
    }

	  /* This macro set a item in the correct order. I use it for
	   * the different elements (subject, property, ...): */
#define B_SYNC_TCACHE( x , y ) \
	  if (!caches[numb]->x) \
	    { \
	      for (i = numb; i > 0; i--) \
		tmap.y[i] = tmap.y[i - 1]; \
              \
	      tmap.y[0] = B_TMAP_SET(numb, B_TMAP_VALUE_EMPTY); \
	    } \
	  else \
	    { \
	      for (i = b = 0; i < B_TMAP_NUMB; i++) \
		{ \
	          int value; \
                  \
		  value = B_TMAP_DATA (tmap.y[i]); \
                  \
		  if (!tmap.map[value] || B_TMAP_VALUE (tmap.y[i]) == \
		      B_TMAP_VALUE_EMPTY) \
		    continue; \
                  \
		  if (!caches[value]) \
		    { \
                      if (!(caches[value] = \
			  (b_tcache_t *) calloc (1, sizeof (b_tcache_t)))) \
	                return B_ERROR_MEMORY; \
                      \
                      b_io_seek (data->triples_io, pointer + value * \
				 B_TRIPLE_SIZE + sizeof(b_tmap_t), \
				 SEEK_SET); \
		      \
                      B_SYNC_GET (subject_uri, subject_uri_len, \
	 			     B_TYPE_URI); \
                      B_SYNC_GET (subject_bnode, subject_bnode_len, \
				     B_TYPE_BNODE); \
                      B_SYNC_GET (property, property_len, B_TYPE_PROPERTY); \
                      B_SYNC_GET (object_uri, object_uri_len, \
				     B_TYPE_URI); \
                      B_SYNC_GET (object_bnode, object_bnode_len, \
				     B_TYPE_BNODE); \
                      B_SYNC_GET (object_literal, object_literal_len, \
				     B_TYPE_LITERAL); \
                      B_SYNC_GET (context, context_len, B_TYPE_CONTEXT); \
                      B_SYNC_GET (datatype, datatype_len, B_TYPE_DATATYPE); \
                      B_SYNC_GET (lang, lang_len, B_TYPE_LITERAL); \
                      \
		      caches_free[value]=1; \
		    } \
                  \
		  switch (b_hash_compare \
			  (caches[numb]->x->hash, caches[value]->x->hash)) \
		    { \
		    case -1: \
		      for (j = numb; j > i; j--) \
			tmap.y[j] = tmap.y[j - 1]; \
                      \
		      tmap.y[i] = B_TMAP_SET(numb, B_TMAP_VALUE_FULL); \
		      b = 1; \
		      break; \
                      \
		    case 0: \
		      for (j = numb; j > i + 1; j--) \
			tmap.y[j] = tmap.y[j - 1]; \
                      \
		      tmap.y[i + 1] = B_TMAP_SET(numb, B_TMAP_VALUE_FULL); \
		      b = 1; \
		      break; \
                    \
		    default: \
		      break; \
		    } \
                  \
		  if (b) \
		    break; \
		} \
              \
	      if (!b) \
		tmap.y[numb] = B_TMAP_SET(numb, B_TMAP_VALUE_FULL); \
	    }

	  /* Correct position in the map: */
	  B_SYNC_TCACHE (subject_uri, subjects_uri);
	  B_SYNC_TCACHE (subject_bnode, subjects_bnode);

	  B_SYNC_TCACHE (property, properties);

	  B_SYNC_TCACHE (object_uri, objects_uri);
	  B_SYNC_TCACHE (object_bnode, objects_bnode);
	  B_SYNC_TCACHE (object_literal, objects_literal);

	  B_SYNC_TCACHE (context, contexts);
	  B_SYNC_TCACHE (datatype, datatypes);
	  B_SYNC_TCACHE (lang, langs);
	}

      /* If I don't need a sync for this map: */
      if (!tosync)
	continue;

      /* Map in the head... */
      if (fromtempty == 0)
	{
	  b_string_t *str;

	  /* Creating of the b_string_new_callback: */
	  write_data.io = data->triples_io;
	  write_data.max_cache = data->max_cache;

	  if ((error =
	       b_string_new_callback (&str, b_sync_write, data->max_cache,
				      &write_data)) != B_OK)
	    return error;

	  b_journaling_new (data, data->triples_io,
			    B_JOURNALING_END_WRITE, pointer);

	  b_string_add (str, (unsigned char *) &tmap, sizeof (tmap));

	  /* ...and later the triples: */
	  for (i = 0; i < B_TMAP_NUMB; i++)
	    {
	      /* If I have it: */
	      if (i < numb && caches[i])
		{
#define B_SYNC_TCACHE2( x ) \
		if (caches[i]->x) \
		  { \
		    b_hash_copy (tmap_item.hash, caches[i]->x->hash); \
		    tmap_item.pointer = caches[i]->x->pointer; \
		  } \
		else \
		  memset (&tmap_item, 0, sizeof (b_tmap_item_t)); \
                \
		b_string_add (str, (unsigned char *)&tmap_item, \
                              sizeof (b_tmap_item_t));

		  B_SYNC_TCACHE2 (subject_uri);
		  B_SYNC_TCACHE2 (subject_bnode);
		  B_SYNC_TCACHE2 (property);
		  B_SYNC_TCACHE2 (object_uri);
		  B_SYNC_TCACHE2 (object_bnode);
		  B_SYNC_TCACHE2 (object_literal);
		  B_SYNC_TCACHE2 (context);
		  B_SYNC_TCACHE2 (datatype);
		  B_SYNC_TCACHE2 (lang);
		}

	      /* else empty value: */
	      else
		b_string_add (str, empty, sizeof (empty));
	    }

	  /* Destroy of the b_string_t: */
	  b_string_destroy (str, NULL);

	  b_journaling_destroy (data);
	}
      else
	{
	  b_uint64 pnew = pointer;

	  pnew = b_io_seek (data->triples_io, pointer, SEEK_SET);

	  b_journaling_new (data, data->triples_io, B_JOURNALING_WRITE,
			    pnew, sizeof (b_tmap_t), NULL);

	  if (b_io_write
	      (data->triples_io, &tmap, sizeof (b_tmap_t),
	       data->max_cache) <= 0)
	    {
	      b_journaling_destroy (data);
	      return B_ERROR_INTERNAL;
	    }

	  for (i = 0; i < B_TMAP_NUMB; i++)
	    {
	      if (i < numb && caches[i] && caches_free[i])
		{
#define B_SYNC_TCACHE3( x ) \
		if (caches[i]->x) \
		  { \
		    b_hash_copy (tmap_item.hash, caches[i]->x->hash); \
		    tmap_item.pointer = caches[i]->x->pointer; \
		  } \
		else \
		  memset (&tmap_item, 0, sizeof (b_tmap_item_t)); \
                \
                b_journaling_new (data, data->triples_io, \
				  B_JOURNALING_WRITE, pnew, \
			          sizeof(b_tmap_item_t), NULL); \
		\
	        if (b_io_write (data->triples_io, &tmap_item, \
			        sizeof (b_tmap_item_t), data->max_cache) \
		    <= 0) \
		  { \
		    b_journaling_destroy (data); \
	            return B_ERROR_INTERNAL; \
		  }

		  B_SYNC_TCACHE3 (subject_uri);
		  B_SYNC_TCACHE3 (subject_bnode);
		  B_SYNC_TCACHE3 (property);
		  B_SYNC_TCACHE3 (object_uri);
		  B_SYNC_TCACHE3 (object_bnode);
		  B_SYNC_TCACHE3 (object_literal);
		  B_SYNC_TCACHE3 (context);
		  B_SYNC_TCACHE3 (datatype);
		  B_SYNC_TCACHE3 (lang);
		}
	      else
		pnew = b_io_seek (data->triples_io, B_TRIPLE_SIZE, SEEK_CUR);
	    }

	  b_journaling_destroy (data);
	}

      for (i = 0; i < B_TMAP_NUMB; i++)
	if (caches_free[i])
	  b_tcache_destroy_single (NULL, NULL, caches[i]);

      if ((error = b_tempty_check (data, &tmap, pointer, 1)) != B_OK)
	return error;
    }

  return B_OK;
}

/* This function is the callback for the b_string_new_with_callback */
static b_int64
b_sync_write (unsigned char *what, b_uint64 size, void *dummy)
{
  struct b_sync_data_t *data = (struct b_sync_data_t *) dummy;

  B_LOG3 ("b_sync_write: %p %d %p", what, (int) size, dummy);

  return b_io_write (data->io, what, size, data->max_cache);
}

/* This function change the instances value */
b_error_t
b_sync_instances (b_t * data, b_tcache_t * cache, char add)
{
  b_error_t ret;

  if (cache->subject_uri
      && (ret =
	  b_sync_instances_cache (data, cache->subject_uri, B_TYPE_URI,
				  add)) != B_OK)
    return ret;

  if (cache->subject_bnode
      && (ret =
	  b_sync_instances_cache (data, cache->subject_bnode, B_TYPE_BNODE,
				  add)) != B_OK)
    return ret;

  if (cache->property
      && (ret =
	  b_sync_instances_cache (data, cache->property, B_TYPE_PROPERTY,
				  add)) != B_OK)
    return ret;

  if (cache->object_uri
      && (ret =
	  b_sync_instances_cache (data, cache->object_uri, B_TYPE_URI,
				  add)) != B_OK)
    return ret;

  if (cache->object_bnode
      && (ret =
	  b_sync_instances_cache (data, cache->object_bnode, B_TYPE_BNODE,
				  add)) != B_OK)
    return ret;

  if (cache->object_literal
      && (ret =
	  b_sync_instances_cache (data, cache->object_literal, B_TYPE_LITERAL,
				  add)) != B_OK)
    return ret;

  if (cache->context
      && (ret =
	  b_sync_instances_cache (data, cache->context, B_TYPE_CONTEXT,
				  add)) != B_OK)
    return ret;

  if (cache->datatype
      && (ret =
	  b_sync_instances_cache (data, cache->datatype, B_TYPE_DATATYPE,
				  add)) != B_OK)
    return ret;

  if (cache->lang
      && (ret =
	  b_sync_instances_cache (data, cache->lang, B_TYPE_LITERAL,
				  add)) != B_OK)
    return ret;

  return B_OK;
}

static b_error_t
b_sync_instances_cache (b_t * data, b_cache_t * cache, b_type_t type,
			char add)
{
  b_error_t error;
  b_io_t *io;
  b_uint64 pointer;
  b_uint64 instances;

  if ((error = b_get_type_internal (data, type, &io)) != B_OK)
    return error;

  pointer = cache->pointer + B_HASH_SIZE + sizeof (b_uint64);
  b_io_seek (io, pointer, SEEK_SET);

  if (b_io_read (io, &instances, sizeof (instances)) <= 0)
    return B_ERROR_INTERNAL;

  b_journaling_new (data, io, B_JOURNALING_WRITE, pointer,
		    sizeof (b_uint64), &instances);

  instances += (add > 0 ? 1 : -1);

  b_io_seek (io, pointer, SEEK_SET);

  if (b_io_write (io, &instances, sizeof (instances), data->max_cache) <= 0)
    {
      b_journaling_destroy (data);
      return B_ERROR_INTERNAL;
    }

  b_journaling_destroy (data);

  if (instances <= 0)
    return b_remove_type_cache (data, io, cache);

  return B_OK;
}

/* EOF */
