package org.etsi.mts.tdl.resources;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Enumeration;

import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;

public class ResourceHandler {
	public static URI getSourceUri(Class c, String bundleName, String source) throws URISyntaxException {
		URI uri = new File(source).toURI();
		//FIXED: also for TO? -> should work with all now
		if (Platform.isRunning()) {
			//System.out.println("Running as plugin...");
			Bundle bundle = Platform.getBundle(bundleName);
			URL url = bundle.getEntry(source);
			uri = url.toURI();
		} else {
			//WS
			//TODO: this does not work with exported JAR
			
//			String binPath=this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
//			String projectPath = new File(binPath).getParent();
//			uri = new File(projectPath+"/"+source).toURI();
			uri = getResourceFile(c, source);
		}
		return uri;
	}
	
	//TODO: simplify
	public static URI getResourceFile(Class c, String relativePath)
	{
	    URI uri = null;
	    URL location = c.getProtectionDomain().getCodeSource().getLocation();
	    String codeLocation = location.toString();
	    try{
	        if (codeLocation.endsWith(".jar")) {
	            //Call from jar
	        	//DONE: this does not work.. -> fixed
	        	//should get file out of jar / bundle instead
	        	//TODO: simplify and merge with above, test other cases
	        	//TODO: generalise for use in other cases, e.g. for docx and others?
	        	try {
					Enumeration<URL> resources = ClassLoader.getSystemResources(relativePath.replaceAll("epsilon/", ""));
					URL nextElement = resources.nextElement();
					uri = nextElement.toURI();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
//	            Path path = Paths.get(location.toURI()).resolve("../classes/" + relativePath.replaceAll("epsilon/", "")).normalize();
//	            file = path.toFile();
//	            System.out.println("File: "+file);
	        }else{
	            //Call from IDE
	        	//TODO: remove hardcoded container directory filtering
	            URL resource = c.getClassLoader().getResource(relativePath.replaceAll("(epsilon|resource)/", ""));
				uri = resource.toURI();
//	            file = new File(resource.getPath());
	        }
	    }catch(URISyntaxException ex){
	        ex.printStackTrace();
	    }
	    return uri;
	}

}
