/*
* Copyright (c) 2003 by Windward Studios, Inc. All rights reserved.
*
* This software is the confidential and proprietary information of
* Windward Studios ("Confidential Information").  You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Windward Studios, Inc.
*/

package net.windward.util;

import java.io.*;
import java.lang.reflect.*;
import java.util.*;

import com.lowagie.text.*;
import org.apache.log4j.Logger;
import org.apache.regexp.*;

/**
 * This registers all of the fonts on a system.
 *
 * @author David Thielen
 * @version 1.0  January 24, 2003
 */

public class RegisterFonts {

	static Logger log = Logger.getLogger(RegisterFonts.class);

	static private Method stringMatch = null;

	// used to select the files in the directory
	static class FontName implements FilenameFilter {

		Object regExp;
		String spec;

		FontName(String name) {

			spec = name;

			if (stringMatch == null)
				try {
					regExp = new RE(name);
				} catch (Exception rse) {
					regExp = null;
				}
		}

		public boolean accept(File dir, String name) {

			if (stringMatch != null) {
				Object[] params = new Object[1];
				params[0] = spec;
				try {
//					return name.toLowerCase().matches( spec );
					Object rtn = stringMatch.invoke(name.toLowerCase(), params);
					return ((Boolean) rtn).booleanValue();
				} catch (Exception e) {
					log.info(e);
				}
				return false;
			}
			return ((RE) regExp).match(name.toLowerCase());
		}
	}

	public static void registerFonts(String path, String name) {

		// requires 1.4 or greater for String.matches()
		String ver = System.getProperty("java.specification.version");
		if ((ver.charAt(0) > '1') || (ver.charAt(2) >= '4')) {
			Class params[] = new Class[1];
			params[0] = path.getClass();
			try {
				stringMatch = path.getClass().getMethod("matches", params);
			} catch (NoSuchMethodException nsme) {
			}
		}

		// if no String.match, check for regexp
		if (stringMatch == null) {
			try {
				RE regExp = new RE("dave");
			} catch (NoClassDefFoundError cnfe) {
				System.out.println();
				System.out.println("regexp.jar is not in your classpath.");
				System.out.println("you can download regexp.jar at http://jakarta.apache.org/regexp");
				System.out.println();
				System.out.println("your classpath is: " + System.getProperty("java.class.path"));
				System.out.println();
				throw cnfe;
			} catch (Exception rse) {
				log.error(rse);
				return;
			}
		}

		File fil = new File(path);
		String[] all = fil.list(new FontName(name));
		if (all != null)
			for (int ind = 0; ind < all.length; ind++)
				FontFactory.register(path + all[ind]);
	}

	public static void registerDefaultFonts() {

		String os = System.getProperty("os.name");
		log.info("registerDefaultFonts OS = " + os);

		if ((os.length() >= 7) && (os.substring(0, 7).compareToIgnoreCase("windows") == 0)) {
			registerFonts("c:/windows/fonts/", ".*\\.ttf");
			registerFonts("c:/windows/fonts/", ".*\\.ttc");
			registerFonts("c:/winnt/fonts/", ".*\\.ttf");
			registerFonts("c:/winnt/fonts/", ".*\\.ttc");
		}
		if (((os.length() >= 5) && (os.substring(0, 5).compareToIgnoreCase("SunOS") == 0)) ||
				((os.length() >= 7) && (os.substring(0, 7).compareToIgnoreCase("solaris") == 0))) {
			registerFonts("/usr/X/lib/X11/fonts/TrueType/", ".*\\.ttf");
			registerFonts("/usr/X/lib/X11/fonts/TrueType/", ".*\\.ttc");
			registerFonts("/usr/openwin/lib/X11/fonts/TrueType/", ".*\\.ttf");
			registerFonts("/usr/openwin/lib/X11/fonts/TrueType/", ".*\\.ttc");
		}
		if ((os.length() >= 5) && (os.substring(0, 5).compareToIgnoreCase("linux") == 0)) {
			registerFonts("/usr/share/fonts/default/TrueType/", ".*\\.ttf");
			registerFonts("/usr/share/fonts/default/TrueType/", ".*\\.ttc");
			registerFonts("/usr/X11R6/lib/X11/fonts/ttf/", ".*\\.ttf");
			registerFonts("/usr/X11R6/lib/X11/fonts/ttf/", ".*\\.ttc");
		}
	}

	// fonts is in the form path;path;... where each path is the dir & file spec
	public static void registerFontPath(String fontpath) {

		log.info("registerFontPath( " + fontpath + " )");

		// walk it one spec at a time
		StringTokenizer tok = new StringTokenizer(fontpath, ";");
		while (tok.hasMoreTokens()) {
			String spec = tok.nextToken();

			// break into path and file spec
			int ind = spec.lastIndexOf('/');
			int indBack = spec.lastIndexOf('\\');
			ind = Math.max(ind, indBack);
			if (ind == -1)
				return;
			int end = ind + 1;

			// we have to change *.ttf to .*\.ttf
			StringBuffer file = new StringBuffer();
			while (++ind < spec.length()) {
				switch (spec.charAt(ind)) {
					case '*':
						file.append(".*");
						break;
					case '.':
						file.append("\\.");
						break;
					default :
						file.append(spec.charAt(ind));
						break;
				}
			}
			registerFonts(spec.substring(0, end), file.toString());
		}
	}
}

