/* 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>

static int b_triple_compare (b_tcache_t * a, b_tcache_t * b);

/**
 * b_get_type:
 * @data: The pointer to a b_t data struct.
 * @type: The type of the element you are looking for.
 * @what: The data of this element as string.
 * @len: The len of the string (if 0, this function uses strlen on what).
 * @exist: A pointer to a char. It will be 1 if the data exists or 0.
 * @returns: The error code.
 *
 * Searchs a data into the storage.
 */
b_error_t
b_get_type (b_t * data, b_type_t type, unsigned char *what, b_uint64 len,
	    char *exist)
{
  b_cache_t *cache;
  b_error_t error;

  B_LOG5 ("b_get_type: %p %d %p %d %p", data, type, what, (int) len, exit);

  if ((error = b_get_type_cache (data, type, what, len, &cache)) != B_OK)
    {
      b_cache_destroy (cache);
      return error;
    }

  *exist = cache ? 1 : 0;
  b_cache_destroy (cache);
  return B_OK;
}

/* This function gets a item from the list: */
b_error_t
b_get_type_cache (b_t * data, b_type_t type, unsigned char *what,
		  b_uint64 len, b_cache_t ** exist)
{
  unsigned char hash[B_HASH_SIZE];

  B_LOG5 ("b_get_type_cache: %p %d %p %d %p", data, type, what, (int) len,
	  exit);

  if (!data || !what || !exist)
    return B_ERROR_DATA;

  len = len > 0 ? len : strlen ((char *) what);
  b_hash_new (data, what, len, hash);

  return b_get_type_cache_hash (data, type, hash, what, len, exist);
}

/* This function gets a item from the list: */
b_error_t
b_get_type_cache_hash (b_t * data, b_type_t type, unsigned char *hash,
		       unsigned char *what, b_uint64 len, b_cache_t ** exist)
{
  b_uint64 pointer;
  b_error_t error;
  b_io_t *io;
  b_map_t map;
  unsigned char *iwhat = NULL;
  int cmp;

  B_LOG6 ("b_get_type_cache_hash: %p %d %p %p %d %p", data, type, hash, what,
	  (int) len, exit);

  if (!data || !hash || !exist)
    return B_ERROR_DATA;

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

  *exist = NULL;

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

  /* Check in the file: */
  while (1)
    {
      /* hash: */
      if (b_io_read (io, &map, sizeof (map)) <= 0)
	return B_OK;

      cmp = b_hash_compare (hash, map.hash);

      /* Too small? On the left */
      if (cmp < 0 || (cmp == 0 && pointer == sizeof (b_uint64)))
	{
	  if (map.left)
	    {
	      pointer = b_io_seek (io, map.left, SEEK_SET);
	      continue;
	    }
	  else
	    break;
	}

      /* Too big? On the right */
      else if (cmp > 0)
	{
	  if (map.right)
	    {
	      pointer = b_io_seek (io, map.right, SEEK_SET);
	      continue;
	    }
	  else
	    break;
	}

      /* Found! */
      else
	{
	  if (!what)
	    {
	      if (!
		  (iwhat =
		   malloc (sizeof (unsigned char) * (size_t) (map.len + 1))))
		return B_ERROR_MEMORY;

	      if (map.len && b_io_read (io, iwhat, map.len) <= 0)
		{
		  free (iwhat);
		  return B_ERROR_INTERNAL;
		}

	      iwhat[map.len] = 0;
	    }

	  if ((error =
	       b_cache_new (hash, what ? what : iwhat, map.len, pointer,
			    exist)) != B_OK)
	    {
	      if (!what)
		free (iwhat);
	      return error;
	    }

	  if (!iwhat)
	    free (iwhat);
	  return B_OK;
	}
    }

  return B_OK;
}

/* This function gets a item from the list: */
b_error_t
b_get_type_pointer (b_t * data, b_type_t type, b_uint64 pointer,
		    b_cache_t ** exist)
{
  b_error_t error;
  b_io_t *io;
  b_map_t map;
  unsigned char *iwhat;

  B_LOG4 ("b_get_type_pointer: %p %d %d %p", data, type, (int) pointer, exit);

  if (!data || !pointer || !exist)
    return B_ERROR_DATA;

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

  *exist = NULL;

  pointer = b_io_seek (io, pointer, SEEK_SET);

  /* hash: */
  if (b_io_read (io, &map, sizeof (map)) <= 0)
    return B_OK;

  if (!(iwhat = malloc (sizeof (unsigned char) * (size_t) (map.len + 1))))
    return B_ERROR_MEMORY;

  if (map.len && b_io_read (io, iwhat, map.len) <= 0)
    {
      free (iwhat);
      return B_ERROR_INTERNAL;
    }

  iwhat[map.len] = 0;

  if ((error =
       b_cache_new (map.hash, iwhat, map.len, pointer, exist)) != B_OK)
    {
      free (iwhat);
      return error;
    }

  free (iwhat);
  return B_OK;
}

b_error_t
b_get_type_internal (b_t * data, b_type_t type, b_io_t ** io)
{
  B_LOG3 ("b_get_type_internal: %p %d %p", data, type, io);

  if (!data || !io)
    return B_ERROR_DATA;

  switch (type)
    {
    case B_TYPE_URI:
      *io = data->uris_io;
      break;

    case B_TYPE_PROPERTY:
      *io = data->properties_io;
      break;

    case B_TYPE_LITERAL:
      *io = data->literals_io;
      break;

    case B_TYPE_BNODE:
      *io = data->bnodes_io;
      break;

    case B_TYPE_CONTEXT:
      *io = data->contexts_io;
      break;

    case B_TYPE_DATATYPE:
      *io = data->datatypes_io;
      break;

    default:
      return B_ERROR_DATA;
    }

  return B_OK;
}

/**
 * b_get_triple:
 * @data: The pointer to a b_t data struct.
 * @triple: The triple you are looking for.
 * @exist: A pointer to a char. It will be 1 if the data exists or 0.
 * @returns: The error code.
 *
 * Searchs a triple into the storage.
 */
b_error_t
b_get_triple (b_t * data, b_triple_t * triple, char *exist)
{
  b_tcache_t *cache;
  b_error_t error;

  B_LOG3 ("b_get_triple: %p %p %p", data, triple, exist);

  if ((error = b_get_triple_cache (data, triple, &cache)) != B_OK)
    return error;

  *exist = cache ? 1 : 0;
  return B_OK;
}

b_error_t
b_get_triple_cache (b_t * data, b_triple_t * triple, b_tcache_t ** exist)
{
  b_tcache_t *list;
  b_tcache_t *cache;
  b_error_t error;

  b_uint64 pointer;
  b_tmap_t tmap;
  b_tmap_item_t tmap_item;

  int i, j, elements;
  char tmap_results[B_TMAP_NUMB];

  B_LOG3 ("b_get_triple_cache: %p %p %p", data, triple, exist);

  if (!data)
    return B_ERROR_DATA;

  if (b_triple_check (triple) != B_OK)
    return B_ERROR_DATA;

  if (!(cache = (b_tcache_t *) calloc (1, sizeof (b_tcache_t))))
    return B_ERROR_MEMORY;

#define B_GET_FIND( str , len , type , where ) \
  if (where) \
    { \
      b_cache_destroy (where); \
      where = NULL; \
    } \
  \
  if ((error = b_get_type_cache (data, type, str, len, &where)) != B_OK) \
    { \
      b_tcache_destroy_single (NULL, NULL, cache); \
      return error; \
    } \
  \
  if (!where) \
    { \
      b_tcache_destroy_single (NULL, NULL, cache); \
      *exist=0; \
      return B_OK; \
    }

  if (triple->subject_uri)
    {
      B_GET_FIND (triple->subject_uri, triple->subject_uri_len, B_TYPE_URI,
		  cache->subject_uri);
    }
  else
    {
      B_GET_FIND (triple->subject_bnode, triple->subject_bnode_len,
		  B_TYPE_BNODE, cache->subject_bnode);
    }

  B_GET_FIND (triple->property, triple->property_len, B_TYPE_PROPERTY,
	      cache->property);

  if (triple->object_uri)
    {
      B_GET_FIND (triple->object_uri, triple->object_uri_len, B_TYPE_URI,
		  cache->object_uri);
    }

  else if (triple->object_bnode)
    {
      B_GET_FIND (triple->object_bnode, triple->object_bnode_len,
		  B_TYPE_BNODE, cache->object_bnode);
    }

  else if (triple->object_literal)
    {
      B_GET_FIND (triple->object_literal, triple->object_literal_len,
		  B_TYPE_LITERAL, cache->object_literal);
    }

  if (triple->context)
    {
      B_GET_FIND (triple->context, triple->context_len, B_TYPE_CONTEXT,
		  cache->context);
    }

  if (triple->datatype)
    {
      B_GET_FIND (triple->datatype, triple->datatype_len, B_TYPE_DATATYPE,
		  cache->datatype);
    }

  if (triple->lang)
    {
      B_GET_FIND (triple->lang, triple->lang_len, B_TYPE_LITERAL,
		  cache->lang);
    }

  /* Check from the cache list: */
  for (list = data->triples_cache; list; list = list->next)
    {
      if (!b_triple_compare (list, cache))
	{
	  *exist = list;
	  b_tcache_destroy_single (NULL, NULL, cache);
	  return B_OK;
	}
    }

  *exist = NULL;

  if (data->triples_total == data->triples_cache_items)
    {
      b_tcache_destroy_single (NULL, NULL, cache);
      return B_OK;
    }

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

  /* Check in the file: */
  while (1)
    {
      if (b_io_read (data->triples_io, &tmap, sizeof (b_tmap_t)) <= 0)
	{
	  b_tcache_destroy_single (NULL, NULL, cache);
	  return B_OK;
	}

      if ((error = b_tempty_check (data, &tmap, pointer, 0)) != B_OK)
	{
	  b_tcache_destroy_single (NULL, NULL, cache);
	  return error;
	}

      memset (&tmap_results, 0, sizeof (tmap_results));

      /* Disactive no compatible results: */
      for (i = elements = 0; i < B_TMAP_NUMB; i++)
	{
	  if (!tmap.map[i])
	    tmap_results[i] = 1;
	  else
	    elements++;
	}

      /* Disactive no compatible results: */
      for (i = 0; i < elements; i++)
	{
	  if (cache->subject_uri
	      && B_TMAP_VALUE (tmap.subjects_uri[i]) == B_TMAP_VALUE_EMPTY)
	    tmap_results[B_TMAP_DATA (tmap.subjects_uri[i])] = 1;

	  if (cache->subject_bnode
	      && B_TMAP_VALUE (tmap.subjects_bnode[i]) == B_TMAP_VALUE_EMPTY)
	    tmap_results[B_TMAP_DATA (tmap.subjects_bnode[i])] = 1;

	  if (cache->object_uri
	      && B_TMAP_VALUE (tmap.objects_uri[i]) == B_TMAP_VALUE_EMPTY)
	    tmap_results[B_TMAP_DATA (tmap.objects_uri[i])] = 1;

	  if (cache->object_bnode
	      && B_TMAP_VALUE (tmap.objects_bnode[i]) == B_TMAP_VALUE_EMPTY)
	    tmap_results[B_TMAP_DATA (tmap.objects_bnode[i])] = 1;

	  if (cache->object_literal
	      && B_TMAP_VALUE (tmap.objects_literal[i]) == B_TMAP_VALUE_EMPTY)
	    tmap_results[B_TMAP_DATA (tmap.objects_literal[i])] = 1;

	  if (cache->context
	      && B_TMAP_VALUE (tmap.contexts[i]) == B_TMAP_VALUE_EMPTY)
	    tmap_results[B_TMAP_DATA (tmap.contexts[i])] = 1;

	  if (cache->datatype
	      && B_TMAP_VALUE (tmap.datatypes[i]) == B_TMAP_VALUE_EMPTY)
	    tmap_results[B_TMAP_DATA (tmap.datatypes[i])] = 1;

	  if (cache->lang
	      && B_TMAP_VALUE (tmap.langs[i]) == B_TMAP_VALUE_EMPTY)
	    tmap_results[B_TMAP_DATA (tmap.langs[i])] = 1;
	}

#define B_GET_FILE( x , y , n ) \
  if (tmap_results[i]) \
    continue; \
  \
  if (cache->x) \
    { \
      b_io_seek (data->triples_io, pointer + sizeof (b_tmap_t) + i * \
                 B_TRIPLE_SIZE + sizeof(b_tmap_item_t) * n, SEEK_SET); \
      \
      if (b_io_read (data->triples_io, &tmap_item, sizeof (b_tmap_item_t)) \
          <= 0) \
	{ \
          b_tcache_destroy_single(NULL, NULL, cache); \
	  return B_ERROR_INTERNAL; \
	} \
      \
      switch (b_hash_compare (tmap_item.hash, cache->x->hash)) \
	{ \
          case -1: \
            for (j = 0; j < B_TMAP_NUMB; j++) \
              { \
                if (B_TMAP_VALUE (tmap.y[j]) != B_TMAP_VALUE_EMPTY) \
                  { \
                    tmap_results[B_TMAP_DATA(tmap.y[j])] = 1; \
		    if (B_TMAP_DATA(tmap.y[j]) == i) \
		      break; \
                  } \
              } \
            break; \
          \
          case 1: \
            for (j = B_TMAP_NUMB-1; j >= 0; j--) \
              { \
                if (B_TMAP_VALUE (tmap.y[j]) != B_TMAP_VALUE_EMPTY) \
                  { \
                    tmap_results[B_TMAP_DATA(tmap.y[j])] = 1; \
		    if (B_TMAP_DATA(tmap.y[j]) == i) \
		      break; \
                  } \
              } \
            break; \
          \
          case 0: \
          default: \
            break; \
	} \
    }

      for (i = 0; i < B_TMAP_NUMB; i++)
	{
	  B_GET_FILE (subject_uri, subjects_uri, 0);
	  B_GET_FILE (subject_bnode, subjects_bnode, 1);
	  B_GET_FILE (property, properties, 2);
	  B_GET_FILE (object_uri, objects_uri, 3);
	  B_GET_FILE (object_bnode, objects_bnode, 4);
	  B_GET_FILE (object_literal, objects_literal, 5);
	  B_GET_FILE (context, contexts, 6);
	  B_GET_FILE (datatype, datatypes, 7);
	  B_GET_FILE (lang, langs, 8);

	  if (tmap_results[i])
	    continue;

	  if ((error = b_add_triple_cache (data, triple, pointer, i)) != B_OK)
	    {
	      b_tcache_destroy_single (NULL, NULL, cache);
	      return error;
	    }

	  /* Re-exec because the previous function inserts in the cache 
	   * list the element founded */
	  b_tcache_destroy_single (NULL, NULL, cache);
	  return b_get_triple_cache (data, triple, exist);
	}

      pointer =
	b_io_seek (data->triples_io,
		   pointer + sizeof (b_tmap_t) + B_TRIPLE_SIZE * B_TMAP_NUMB,
		   SEEK_SET);
    }

  b_tcache_destroy_single (NULL, NULL, cache);
  return B_OK;
}

static int
b_triple_compare (b_tcache_t * a, b_tcache_t * b)
{
  int c;

  B_LOG2 ("b_triple_compare: %p %p", a, b);

#define B_COMPARE_SINGLE( x ) \
  c = 0; \
  if (a->x) \
    c++; \
  if (b->x) \
    c++; \
  \
  switch (c) \
    { \
    case 0: \
      break; \
    \
    case 1: \
      return 1; \
    \
    default: \
      if (b_hash_compare(a->x->hash, b->x->hash)) \
	return 1; \
      break; \
    }

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

  return 0;
}

/* EOF */
