package org.jcon.util;

import org.jcon.ba.lib.LocaleMgr;
import org.jcon.ui.JImageCanvas;
import org.jcon.ui.MessageBox;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFrame;

/**
 * General library methods. These are all static.
 * Those methods that many classes commonly call should be
 * in this class, so that they only have to import GenLib.
 *
 * Note - Some commented out since not yet used, may be moved.
 *
 * @author Jack Harich
 */

public class GenLib {
    
//---------- Private Fields ------------------------------
private static ProblemController problemController;

//---------- Public Methods ------------------------------
public static void beep() {
    Toolkit.getDefaultToolkit().beep();
}
public static void setProblemController(ProblemController controller) {
    problemController = controller;
}
//---------- error
/**
* This method passes the error to the ProblemController if
* that property is not null, or displays the error.
* This is replaced by displayError(), which is a better name.
*/
public static void error(String methodID, String message) {
    if (problemController == null) {
        displayError(methodID, message);
    } else {
        problemController.processError(methodID, message);   
    }
}
/**
 * This method is used for logical coding errors, such as
 * attempts to pass invalid arguments. It presents the
 * methodID and message to the user in a modal dialog.
 *
 * @param methodID  of the format "ClassName.methodName()".
 * @param message   describes the problem in a manner
 *                  useful to both user and developer.
 */
public static void displayError(String methodID, String message) {
    System.err.println(methodID + " has error: " + message);
    beep();
    MessageBox dialog = new MessageBox();
    dialog.setTitle(" Application Error");
    dialog.askOkayBlock(methodID + "\n\n" + message);
}
//---------- exception
/**
* This method passes the exception to the ProblemController if
* that property is not null, or displays the exception.
*/
public static void exception(String methodID, String message, Exception ex) {
    if (problemController == null) {
        displayException(methodID, message, ex);
    } else {
        problemController.processException(methodID, message, ex);   
    }
}
/**
 * This method is used for exceptions.  It presents the
 * methodID and message to the user in a modal dialog.
 *
 * @param methodID  of the format "ClassName.methodName()".
 * @param message   describes the problem in a manner
 *                  useful to both user and developer.
 * @param ex        the exception that occurred.
 */
public static void displayException(String methodID,
        String message, Exception ex) {
    System.err.println("Exception: " + message);
    Throwable th = (Throwable)ex;
    if (ex instanceof InvocationTargetException) {
        // Not yet fully tested
        th = ((InvocationTargetException)ex).getTargetException();
    }
    th.printStackTrace();
    beep();
    MessageBox dialog = new MessageBox();
    dialog.setTitle(" Application Exception");
    dialog.askOkayBlock(methodID + "\n\n" + message + "\n\n" + th);
}
//---------- Other
/**
 * Presents a modal blocking Dialog with the message and
 * an Okay button. The Dialog disposes itself when the
 * button is clicked. Uses the default locale.
 */
public static void helpfulHint(String message) {
    helpfulHint(message, null, null);
}
/**
* Same as helpfulHint(message) except uses the localeMgr
* to localize the helpful hint window. If localeMgr is
* null then the default locale is used.
*/
public static void helpfulHint(String message, LocaleMgr localeMgr) {
    helpfulHint(message, null, localeMgr);
}
/**
 * This variation uses a supplied frame which is passed to
 * the dialog. (Seldom used since WindowMgr was created)
 */
public static void helpfulHint(String message,
                      JFrame frame) {
	helpfulHint(message, frame, null);                      
} 
/**
* Same as helpfulHint(message, frame) except uses the
* localeMgr to localize the helpful hint window. If 
* localeMgr is null then the default locale is used.
*/
public static void helpfulHint(String message,
                      JFrame frame, LocaleMgr localeMgr) {
    MessageBox dialog = new MessageBox();
    if (frame != null) dialog.setFrame(frame);
    if (localeMgr == null) {
    	dialog.setTitle(" Helpful Hint");
    } else {
    	dialog.setLocaleMgr(localeMgr);
    	String title = localeMgr.getString
    		("UtilitiesJCON", "HelpfulHintWindowTitle");
    	dialog.setTitle(" " + title);
    }
    try {
        // *** Class thisClass = Class.forName("COM.jconsort.util.GenLib");
        JImageCanvas imageCanvas =
            new JImageCanvas(GenLib.class, "LightBulb.gif");
        dialog.useImageCanvas(imageCanvas);
    } catch(Exception ex) {
        exception("GenLib.helpfulHint()", "Cannot load image.", ex);
    }
    dialog.askOkayBlock(message);
}
/**
 * Creates and returns a class instance given className.
 * The class must have a no-arg constructor. Complains and
 * returns null for failure.
 */
public static Object createInstance(String className) {
//print(".createInstance() - " + className);
    try {
        return Class.forName(className).newInstance();

    } catch (ClassNotFoundException ex) {
        exception("GenLib.createInstance()",
            "Cannot find class '" + className, ex);
        return null;

    } catch (Exception ex) {
        exception("GenLib.createInstance()",
            "Cannot create class '" + className, ex);
        return null;
    }
}
/**
 * For prompted pause in DOS window. Pressing ENTER
 * will cause the paused program to continue. Returns
 * the text entered, which may be empty.
 */
public static String readInputLine(String prompt) {
    System.out.print(prompt);
    try {
        BufferedReader input = new BufferedReader(new
            InputStreamReader(System.in) );
        String line = input.readLine();
        //input.close(); Prevents using a second time
        return line;
    } catch(Exception ex) {
        return "#Error in GenLib.readInputLine()#";
    }
}
public static String getClassLastName(Object instance) {
    String className = instance.getClass().getName();
    return DataLib.getLastToken(className, ".");
}
/**
 * Returns null if text is null, otherwise returns
 * text.trim(). This prevents many difficult to debug bugs,
 * since if trim() is called on a null String reference the
 * JVM hangs (currently, Java 1.1.3) or throws a NullPointerException
 * (future, when this Java bug is fixed).
 */
public static String trim(String text) {
    if (text == null) {
        return null;
    } else {
        return text.trim();
    }
}
/**
 * Returns the current datetime in mm/dd/yyyy hh:mm:ss format.
 */
public static String createCurrentDateTime() {
    
    Calendar calendar = Calendar.getInstance();
    String text = "";
    
    // Note month-of-year is zero based, a Java bug
    text += (calendar.get(Calendar.MONTH) + 1) + "/";
    text += calendar.get(Calendar.DAY_OF_MONTH) + "/";
    text += calendar.get(Calendar.YEAR) + " ";
    
    text += calendar.get(Calendar.HOUR_OF_DAY) + ":";
    text += calendar.get(Calendar.MINUTE) + ":";
    text += calendar.get(Calendar.SECOND);
    
    return text;

    /**Date now = new Date();
    String text = "";
    text += (now.getMonth() + 1) + "/"; // 0 based
    text += now.getDate() + "/"; // Day of month
    text += (now.getYear() + 1900) + " ";
    text += now.getHours() + ":";
    text += now.getMinutes() + ":";
    text += now.getSeconds() + "";
    return text; */
}
//---------- Private Methods -----------------------------
//--- Std
private static void print(String text) {
    System.out.println("GenLib" + text);
}

} // End class
