package com.l2client.asset;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Logger;

import com.jme3.asset.DesktopAssetManager;
import com.jme3.export.Savable;
import com.jme3.export.binary.BinaryImporter;
import com.jme3.scene.Node;
import com.jme3.system.JmeSystem;

//FIXME refactor into callable and future
public class AssetManager {

	private static final Logger logger = Logger.getLogger(AssetManager.class
			.getName());

	private com.jme3.asset.AssetManager jmeAssetMan;

	private static AssetManager instance = null;

	private ExecutorService executor =  Executors.newFixedThreadPool(2);//Executors.newSingleThreadExecutor();

	private AssetManager() {
		try {
			jmeAssetMan = new DesktopAssetManager(Thread.currentThread().getContextClassLoader().getResource("com/l2client/asset/loader.cfg"));
		} catch (Exception e) {
			logger.severe("Failed to load com/l2client/asset/loader.cfg, using default assetmanager");
			jmeAssetMan = new DesktopAssetManager(true);
		}
		//FIXME we have to do this somehow better.. ev. in read megaset?
		jmeAssetMan.registerLocator("textures/entity/", "com.jme3.asset.plugins.ClasspathLocator");
	}

	public static AssetManager getInstance() {
		if (AssetManager.instance != null)
			return AssetManager.instance;
		else {
			AssetManager.instance = new AssetManager();
			return AssetManager.instance;
		}
	}

	public void loadAsset(final Asset a, boolean immediate) {
		logger.fine("requested " + a.getLocation());
		Future<Object> ret = executor.submit(new Callable<Object>() {

			@Override
			public Object call() throws Exception {
				Object n = null;

				n = jmeAssetMan.loadAsset(a.getLocation());
				if (n != null) {
					a.setBaseAsset(n);
					logger.fine("requested " + a.getLocation() + " was loaded");
				} else
					logger.severe("requested " + a.getLocation()
							+ " was not found");

				return n;
			}

		});

		a.setFuture(ret);

	}
	
	public com.jme3.asset.AssetManager getJmeAssetMan(){
		return jmeAssetMan;
	}
}
