/* ======================================================================
The Bodington System Software License, Version 1.0

Copyright (c) 2001 The University of Leeds.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1.  Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2.  Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3.  The end-user documentation included with the redistribution, if any,
must include the following acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.

4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.

5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
EVENT SHALL THE UNIVERSITY OF LEEDS OR ITS CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
=========================================================

This software was originally created by the University of Leeds and may contain voluntary
contributions from others.  For more information on the Bodington Open Source Project, please
see http://bodington.org/

====================================================================== */

package org.bodington.i18n;

import org.bodington.database.PrimaryKey;

import java.util.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.ResultSet;

/**
 * Class that handles the localisation of user-displayed text strings.
 * @author Alistair Young
 */
public class Localiser
{
  public static final int DEBUG_OFF = 0;
  public static final int DEBUG_MINIMAL = 1;
  public static final int DEBUG_VERBOSE = 2;

  private ResourceBundle[] resources = null;
  private String[] resourceBundlesNames = null;
  private String resorceBundlesLanguage = null;
  private String errorString = null;
  private boolean resourcesLoaded = false;
  private static int debug = DEBUG_OFF;
  private static Properties cache = new Properties();
  private boolean foundIt = false;

  public Localiser(String resourceFiles, String language) {
    resorceBundlesLanguage = language;

    try {
      // Remove all whitespace, such as line breaks, tabs, spaces that are there for legibility
      String tmpBuffer = "";
      for (int c=0; c < resourceFiles.length(); c++) {
        if (!Character.isWhitespace(resourceFiles.charAt(c))) {
          tmpBuffer += resourceFiles.charAt(c);
        }
      }
      resourceFiles = tmpBuffer;

      String[] buffer = resourceFiles.split(",");
      resources = new ResourceBundle[buffer.length];
      resourceBundlesNames = new String[buffer.length];
      for (int count=0; count < buffer.length; count++) {
        resources[count] = ResourceBundle.getBundle(buffer[count], new Locale(language));
        resourceBundlesNames[count] = buffer[count];
      }
      resourcesLoaded = true;
    }
    catch(NullPointerException npe) {
      errorString = npe.getMessage();
    }
    catch(MissingResourceException mre) {
      errorString = mre.getMessage();
    }
  }

  public void setDebug(int inLevel) {
    debug = inLevel;
  }

  public String getString(String inID) {
    String result = null;

    if (resourcesLoaded) {
      foundIt = false;
      for (int count=0; count < resources.length && !foundIt; count++) {
        try {
          result = resources[count].getString(inID);

          if ((debug == DEBUG_MINIMAL) || (debug == DEBUG_VERBOSE)) {
            result = inID + ":" + result;

            if (debug == DEBUG_VERBOSE)
              result = resourceBundlesNames[count] + "_" + result;
          }

          foundIt = true;
        }
        catch(NullPointerException npe) {
          result = "String not found : " + inID;
        }
        catch(MissingResourceException mre) {
          result = "String not found : " + inID;
        }
      }
      return result;
    }
    else
      return errorString;
  }

  public Enumeration getKeys() {
    return resources[0].getKeys();
  }

  public static void cacheLocalisedString(PrimaryKey inID, String inLanguageCode, String inString) {
    cache.setProperty(String.valueOf(inID.intValue()) + "_" + inLanguageCode, inString);
  }

  /**
   * Gets a localised string from either the cache or the database.
   *
   * @param inID
   * @param inLanguageCode
   * @param inDBConnection
   */
  public static String getLocalisedString(PrimaryKey inID, String inLanguageCode, Connection inDBConnection) {
    // TODO: replace "en" with the default language from bodington.properties
    String localisedString = cache.getProperty(String.valueOf(inID.intValue()) + "_" + inLanguageCode);

    // If the localised string isn't cached yet, get it from the database and cache it
    if (localisedString == null) {
      try {
        Statement sqlQuery = inDBConnection.createStatement();
        String query = null;

        if ((inLanguageCode == null) || (inLanguageCode.equalsIgnoreCase("en")))
          query = "select string from big_strings where big_string_id = '" + inID + "'";
        else
          query = "select string from big_strings_" + inLanguageCode + " where big_string_id = '" + inID + "'";

        ResultSet queryResults = sqlQuery.executeQuery(query);
        if (queryResults.first()) {
          localisedString = queryResults.getString("string");
          if (localisedString != null) {
            cacheLocalisedString(inID, inLanguageCode, localisedString);
          }
        }

        queryResults.close();
        sqlQuery.close();
      }
      catch(SQLException se) {
        localisedString = null;
      }
    }

    if (localisedString != null) {
      /*
      localisedString = (debug || verbose) ? ("DB:" + inID + ":" + localisedString) : localisedString;
      localisedString = (verbose) ? ("big_strings_" + inLanguageCode + ":" + localisedString) : localisedString;
      */
    }

    //return localisedString;
    return null;
  }
}
