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

b_error_t
b_tempty_check (b_t * data, b_tmap_t * tmap, b_uint64 pointer, char remove)
{
  b_tempty_t *te;
  b_uint64 i, value;

  /* Check the number of the empty elements: */
  for (value = i = 0; i < B_TMAP_NUMB; i++)
    if (!tmap->map[i])
      value++;

  if (!value)
    {
      if (data->triples_empty && remove)
	{
	  b_tempty_t *old;
	  for (te = data->triples_empty, old = NULL; te; te = te->next)
	    {
	      if (te->pointer == pointer)
		{
		  if (old)
		    old->next = te->next;
		  else
		    data->triples_empty = te->next;

		  free (te);
		  data->triples_empty_size--;
		  break;
		}

	      old = te;
	    }
	}

      return B_OK;
    }

  /* Is it already in the list? */
  for (te = data->triples_empty; te; te = te->next)
    {
      if (te->pointer == pointer)
	break;

      else if (te->pointer > pointer)
	{
	  te = NULL;
	  break;
	}
    }

  /* I must create a new elements: */
  if (!te)
    {
      if (data->triples_empty_size >= data->max_cache)
	return B_OK;

      if (!(te = calloc (1, sizeof (b_tempty_t))))
	return B_ERROR_MEMORY;

      te->pointer = pointer;

      if (!data->triples_empty)
	data->triples_empty = te;

      else if (pointer <= data->triples_empty->pointer)
	{
	  te->next = data->triples_empty;
	  data->triples_empty = te;
	}
      else
	{
	  b_tempty_t *tmp;

	  for (tmp = data->triples_empty; tmp->next; tmp = tmp->next)
	    {
	      if (tmp->pointer >= pointer)
		{
		  te->next = tmp->next;
		  tmp->next = te;
		  break;
		}
	    }

	  if (!tmp->next)
	    tmp->next = te;
	}

      data->triples_empty_size++;
    }

  return B_OK;
}

char
b_tempty_get (b_t * data, b_tmap_t * tmap, b_uint64 * pointer)
{
  if (!data->triples_empty)
    return 1;

  b_io_seek (data->triples_io, data->triples_empty->pointer, SEEK_SET);
  if (b_io_read (data->triples_io, tmap, sizeof (b_tmap_t)) <= 0)
    return 1;

  *pointer = data->triples_empty->pointer;

  return 0;
}

void
b_tempty_destroy (b_tempty_t ** list)
{
  b_tempty_t *next;

  while (*list)
    {
      next = (*list)->next;
      free (*list);
      *list = next;
    }
}

/* EOF */
