/** BEGIN COPYRIGHT BLOCK
 * Copyright (C) 2001 Sun Microsystems, Inc.  Used by permission.
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; version 2
 * of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * END COPYRIGHT BLOCK **/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "i18n.h"

#include "getstrmem.h"

char*
XP_GetStringFromMemory(char* strLibraryName,int iToken);


char*
XP_GetStringFromDatabase(char* strLibraryName,
                         char* strLanguage,
                         int key)
{
    char *result = NULL;

    /* we should eventually port this to use proper adminutil
       resources, but for now, only the in-memory resource
       model is supported */
    if (result == NULL)
        result = XP_GetStringFromMemory(strLibraryName,key);
    return result;
}


char*
XP_GetStringFromMemory(char* strLibraryName,int iToken)
{
  /*
   * In memory model called by XP_GetStringFromDatabase
   * does not use database (nsres, et al.).
   *
   * This function uses hash table for library lookup
   * and direct lookup for string.
   *
   * This function is thread safe.
   */


  unsigned hashKey;
  int      found = 0;
  unsigned uToken = iToken;
  char*    cPtr;
  DATABIN* pBucket;

  /* calculate hash key */
  hashKey = 0;
  cPtr = strLibraryName;
  while (*cPtr) {
	hashKey += *(cPtr++);
  }
  hashKey &= BUCKET_MASK;

  /* get bucket for this hash key */
  pBucket = buckets[hashKey];

  /* search overflow buckets */
  while (*(pBucket->pLibraryName)!='\0') {
    if (strcmp(pBucket->pLibraryName,strLibraryName)==0) {
	  found = 1;
	  break;
    }
    pBucket++;
  }

  if (!found) {
    return emptyString;
  }

  if (uToken<=pBucket->numberOfStringsInLibrary) {
      return pBucket->pArrayOfLibraryStrings[uToken];
    } else {
	  /* string token out of range */
      return emptyString;
    }

}
