
package net.lamot.java.jskype.windows;

import java.util.Vector;

import net.lamot.java.jskype.general.AbstractMessenger;
import net.lamot.java.jskype.general.MessageListenerInterface;



/**
* Copyright (C) 2004  B. Lamot
 ***********************************************************
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 ************************************************************
 *
 * Basic class needed to load the dll and stuff....
 * Maybe to be named differently later, i couldnt think of a good name right now
 */
public class Messenger extends AbstractMessenger{
	
	private static Vector listeners = new Vector();
	private static Messenger _instance = null;
	
	/*
	 * Must be called before images are loaded and instances are created.
	 **/
	public boolean initialize()
	{
		System.out.println("Messenger.initialize()");
		_instance = this;
		//	 Load JNI library
		try
		{
			System.loadLibrary( "JSkype" );
			nativeInit();				
		}
		catch( UnsatisfiedLinkError x )
		{
			x.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean sendMessage(String message) {
		System.out.println("Messenger.sendMessage()");
		try {
			nativeSendMessage(message.trim()+" ");
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	public void destroy() {
		System.out.println("Messenger.destroy()");
		try {
			nativeDestroy();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private synchronized static native int nativeSendMessage( String message ) throws UnsatisfiedLinkError;
	private synchronized static native int nativeDestroy() throws UnsatisfiedLinkError;
	private synchronized static native int nativeInit() throws UnsatisfiedLinkError;
	
	/* This override the AbstractMessenger's addListener, bug fixed by Wei Li,
         public void addListener(MessageListenerInterface listener) {
		listeners.add(listener);
	}*/
	
	/**
	 * This method is called by the dll when a skype message is received.
	 * @param skypeID the ID of the Skype instance
	 * @param message the message received
	 */
	public static void onCallback(final int skypeID,final String message) {
		System.out.println("Messenger.onWindowsMessage(); Message from Skype("+skypeID+"): "+message);
		_instance.onMessageReceived(message);		
	}
	
	/**
	 * Called by the dll when a skype instance is found.
	 *
	 */
	public static void onSkypeFound(){
		System.out.println("Skype instance found");
		_instance.onMessageReceived("SkypeControlAPI");
	}

}
