/**
 * This package provides classes to handle video in Processing. The API is compatible with the built-in video library of Processing. 
 * GSVideo uses the multimedia toolkit GStreamer (http://www.gstreamer.net/)  through the gstreamer-java bindings by Wayne Meissener:
 * http://code.google.com/p/gstreamer-java/ 
 * @author Andres Colubri
 * @version 0.5.0.1
 *
 * Copyright (c) 2008 Andres Colubri
 *
 * This source is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This code 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
 * General Public License for more details.
 * 
 * A copy of the GNU General Public License is available on the World
 * Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also
 * obtain it by writing to the Free Software Foundation,
 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

package codeanticode.gsvideo;

import java.util.HashMap;
import java.util.Map;

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;

// Library loader class by Tal Shalif
public class JnaLibLoaderChain {

    public interface DummyLibrary extends Library {
    }    
    
    private static JnaLibLoaderChain instance;

    static final Object[][] WIN32_DEPENDENCIES = {    	
        { "intl", new String[] { }, true },
        { "iconv", new String[] { }, true },
        { "oil-0.3", new String[] { }, true },
        
    	{ "glib-2.0", new String[] { }, true },
        { "gmodule-2.0", new String[] { "glib-2.0" }, true },
        { "gobject-2.0", new String[] { "glib-2.0" }, true },
        { "gthread-2.0", new String[] { "glib-2.0" }, true },

        { "mp3lame", new String[] { }, false },
        { "eay32", new String[] { }, false },
        { "faacdrm", new String[] { }, false },
        { "dvdcss-2", new String[] { }, false },
        { "mms", new String[] { "glib-2.0" }, false },
        { "ogg", new String[] { }, false },
        { "theora", new String[] { "ogg" }, false },
        { "vorbis", new String[] { "ogg" }, false },    
        { "ssleay32", new String[] { "eay32" }, false },
        { "xvidcore", new String[] { }, false },
        { "zlib1", new String[] { }, false },
        { "xml2", new String[] { "iconv", "zlib1"}, false },
        { "glew32", new String[] { }, false },
        
        { "gstreamer-0.10", new String[] { "glib-2.0", "gobject-2.0", "gthread-2.0", "gmodule-2.0" }, true },
        { "gstbase-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstreamer-0.10" }, true },

        { "gstcontroller-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstreamer-0.10" }, true },
        { "gstdataprotocol-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstreamer-0.10" }, true},        
        { "gstdshow-0.10", new String[] { "glib-2.0" }, true },
        { "gstfft-0.10", new String[] { "glib-2.0" }, true }, 
        { "gstinterfaces-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstreamer-0.10" }, true },
        { "gstnet-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstreamer-0.10" }, true },
        { "gstnetbuffer-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstreamer-0.10" }, true },
        { "gstpbutils-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstreamer-0.10" }, true },
        { "gstphotography-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstreamer-0.10" }, true },
        
        { "gstapp-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstbase-0.10", "gstreamer-0.10" }, true },
        { "gstaudio-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstbase-0.10", "gstreamer-0.10", "gstinterfaces-0.10" }, true },
         
        { "gstriff-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstreamer-0.10", "gstaudio-0.10", "gsttag-0.10" }, true },
        { "gstrtp-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstbase-0.10", "gstreamer-0.10" }, true },
        { "gstrtsp-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstreamer-0.10" }, true },
        { "gstsdp-0.10", new String[] { "glib-2.0" }, true },
        { "gsttag-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstbase-0.10", "gstreamer-0.10" }, true },
        { "gstvideo-0.10", new String[] { "glib-2.0", "gobject-2.0", "gstbase-0.10", "gstreamer-0.10" }, true },
                
        { "gstgl-0.10", new String[] { "glew32", "glib-2.0", "gobject-2.0", "gstbase-0.10", "gstreamer-0.10", "gstvideo-0.10" }, false },
    };
    
    static final Object[][] OSX_DEPENDENCIES = {
        { "intl", new String[] { }, true },    	
        { "oil-0.3", new String[] { "intl" }, true },
        
        { "ogg", new String[] { "intl" }, false },
        { "vorbis", new String[] { "ogg" }, false },
        { "vorbisenc", new String[] { "vorbis" }, false },
        { "vorbisfile", new String[] { "vorbis" }, false },
        { "theora", new String[] { "ogg" }, false },
        { "theoradec", new String[] { "intl" }, false },
        { "theoraenc", new String[] { "theoradec", "ogg" }, false },
        { "FLAC", new String[] { "intl" }, false },
        
    	{ "glib-2.0", new String[] { "intl" }, true },
        { "gmodule-2.0", new String[] { "glib-2.0" }, true },
        { "gobject-2.0", new String[] { "glib-2.0" }, true },
        { "gthread-2.0", new String[] { "glib-2.0" }, true },

        { "gstreamer-0.10", new String[] { "gobject-2.0", "gthread-2.0", "gmodule-2.0" }, true },
        { "gstbase-0.10", new String[] { "gstreamer-0.10" }, true },

        { "gstcontroller-0.10", new String[] { "gstreamer-0.10" }, true },
        { "gstdataprotocol-0.10", new String[] { "gstreamer-0.10" }, true },
        { "gstinterfaces-0.10", new String[] { "gstreamer-0.10" }, true },
        { "gstnet-0.10", new String[] { "gstreamer-0.10" }, true },
        { "gstnetbuffer-0.10", new String[] { "gstreamer-0.10" }, true },
        { "gstpbutils-0.10", new String[] { "gstreamer-0.10" }, true },
        
        { "gstaudio-0.10", new String[] { "gstbase-0.10", "gstinterfaces-0.10" }, true },
        { "gstcdda-0.10", new String[] { "gsttag-0.10", "gstbase-0.10" }, true },
        { "gstfft-0.10", new String[] { "gstreamer-0.10" }, true },        
        { "gstriff-0.10", new String[] { "gstaudio-0.10", "gstinterfaces-0.10", "gsttag-0.10",  "gstbase-0.10" }, true },
        { "gstrtp-0.10", new String[] { "gstbase-0.10" }, true },
        { "gstrtsp-0.10", new String[] { "gstreamer-0.10" }, true },
        { "gstsdp-0.10", new String[] { "gstreamer-0.10" }, true },
        { "gsttag-0.10", new String[] { "gstbase-0.10" }, true },
        { "gstvideo-0.10", new String[] { "gstbase-0.10" }, true }
    };
    
    static final Object[][] DEFAULT_DEPENDENCIES = {
        { "gstreamer-0.10", new String[] { }, true },
        { "gstbase-0.10", new String[] { "gstreamer-0.10"  }, true },
        { "gstinterfaces-0.10", new String[] { "gstreamer-0.10" }, true },
        { "gstcontroller-0.10", new String[] { "gstreamer-0.10"  }, true },
        { "gstaudio-0.10", new String[] { "gstbase-0.10" }, true },
        { "gstvideo-0.10", new String[] { "gstbase-0.10" }, true },
    };
    
    static final Object[][] dependencies = Platform.isWindows() ? WIN32_DEPENDENCIES : 
    	                                   Platform.isMac()     ? OSX_DEPENDENCIES : 
	                                	                          DEFAULT_DEPENDENCIES; 
    
    private static final Map<String, Object> loadedMap = new
HashMap<String, Object>();

    private static final int RECURSIVE_LOAD_MAX_DEPTH = 5;

    private JnaLibLoaderChain() {
    }

    private void preLoadLibs() {
        for (Object[] a : dependencies) {
        	load(a[0].toString(), DummyLibrary.class, true, 0, (Boolean)a[2]);
        }
    }

    private String[] findDeps(String name) {

        for (Object[] a : dependencies) {
            if (name.equals(a[0])) {

                return (String[]) a[1];
            }
        }

        return new String[] {}; // library dependancy load chain unspecified - probably client call
    }

    public Object load(String name, Class<?> clazz, boolean reqLib) {
        return load(name, clazz, true, 0, reqLib);
    }

    private Object load(String name, Class<?> clazz, boolean
forceReload, int depth, boolean reqLib) {

        assert depth < RECURSIVE_LOAD_MAX_DEPTH: String.format("recursive max load depth %s has been exceeded", depth);

        Object library = loadedMap.get(name);

        if (null == library || forceReload) {

            //Logger.getAnonymousLogger().info(String.format("%" + ((depth + 1) * 2) + "sloading %s", "->", name));

            try {
                String[] deps = findDeps(name);
                
                for (String lib : deps) {
                    load(lib, DummyLibrary.class, false, depth + 1, reqLib);
                }

                library = loadLibrary(name, clazz, reqLib);

                if (library != null) loadedMap.put(name, library);
            } catch (Exception e) {
            	if (reqLib)
                    throw new RuntimeException(String.format("can not load library %s", name, e));
            	else
            		System.out.println(String.format("can not load library %s", name, e));
            }
        }

        return library;
    }

    private static Object loadLibrary(String name, Class<?> clazz, boolean reqLib) {

        //Logger.getAnonymousLogger().info(String.format("loading %s", name));

        String[] nameFormats;
        nameFormats = Platform.isWindows() ? new String[]{ "%s", "lib%s", "lib%s-0" } : new String[]{ "%s-0", "%s" };
        
        
        UnsatisfiedLinkError linkError = null;

        for (String fmt : nameFormats) {
            try {
            	String s = String.format(fmt, name);
            	//System.out.println("Trying to load library file " + s);
            	Object obj = Native.loadLibrary(s, clazz);
            	//System.out.println("Loaded library " + s + " succesfully!");
                return obj;
            } catch (UnsatisfiedLinkError ex) {
                linkError = ex;
            }
        }
        
    	if (reqLib)
    		throw new UnsatisfiedLinkError(String.format("can't load library %s (%1$s|lib%1$s|lib%1$s-0) with -Djna.library.path=%s. Last error:%s" , name, System.getProperty("jna.library.path"), linkError));
    	else
    	{
    		System.out.println(String.format("can't load library %s (%1$s|lib%1$s|lib%1$s-0) with -Djna.library.path=%s. Last error:%s" , name, System.getProperty("jna.library.path"), linkError));
    		return null;
    	}
    }

    public static synchronized JnaLibLoaderChain getInstance() {

        if (null == instance) {        	
            instance = new JnaLibLoaderChain();
            instance.preLoadLibs();
        }

        return instance;
    }

}
