/*
 * This file is part of the Poliqarp suite.
 * 
 * Copyright (C) 2009, 2010 by Instytut Podstaw Informatyki Polskiej
 * Akademii Nauk (IPI PAN; Institute of Computer Science, Polish
 * Academy of Sciences; cf. www.ipipan.waw.pl).  All rights reserved.
 * 
 * This file may be distributed and/or modified under the terms of the
 * GNU General Public License version 2 as published by the Free Software
 * Foundation and appearing in the file gpl.txt included in the packaging
 * of this file.  (See http://www.gnu.org/licenses/translations.html for
 * unofficial translations.)
 * 
 * A commercial license is available from IPI PAN (contact
 * Michal.Ciesiolka@ipipan.waw.pl or ipi@ipipan.waw.pl for more
 * information).  Licensees holding a valid commercial license from IPI
 * PAN may use this file in accordance with that license.
 * 
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
 * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 */

#include <stdlib.h>

#include <bp/common.h>
#include <bp/ng/meta-key.h>

static const size_t value_hash_table_size = 16;

void meta_key_create(struct meta_key *this)
{
   int rc;
   this->names = list_empty;
   this->type = META_TYPE_STRING;
   this->paths = list_empty;
   this->multiple = false;
   this->required = false,
   this->xmlns = NULL;
   rc = create_hash_table(&this->values, value_hash_table_size,
      HASHTABLE_DUPLICATE_KEYS, NULL);
   if (rc != 0)
      bp_system_error("memory allocation error");
};

void meta_key_destroy(struct meta_key *this)
{
   if (this == NULL)
      return;
   list_destroy(&this->names, free);
   list_destroy(&this->paths, free);
   destroy_hash_table(&this->values, NULL);
}

void meta_key_free(void *this)
{
   meta_key_destroy(this);
   free(this);
}

void meta_key_add_value(struct meta_key *this, const char *value)
{
   hash_table_set(&this->values, value, this);
}

bool meta_key_has_value(struct meta_key *this, const char *value)
{
   return hash_table_const_get(&this->values, value) != NULL;
}

const char* meta_key_get_name(const struct meta_key *this)
{
   assert(this != NULL);
   if (this->names.length == 0)
      return 0;
   return (const char*) this->names.items[0];
}

int meta_key_validate(const struct meta_key *this)
{
   const char *name;
   int rc = 0;
   if (this == NULL)
      return 0;
   name = meta_key_get_name(this);
   if (name == NULL) {
      bp_warning("a meta key without a name");
      return -1;
   }
   size_t n_values = hash_table_num_items(&this->values);
   if (this->type == META_TYPE_ENUM && n_values == 0) {
      bp_warning("meta key \"%s\" has enum type but no enumerated values", name);
      rc = -1;
   }
   if (this->type != META_TYPE_ENUM && n_values > 0) {
      bp_warning("meta key \"%s\" has spurious enumerated values", name);
   }
   return rc;
}
