/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed 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.

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

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;
  }
}
