package org.gcube.portlets.user.speciesdiscovery.server.util;

import java.io.InputStream;
import java.net.MalformedURLException;

import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.gcube.contentmanagement.blobstorage.service.IClient;
import org.gcube.contentmanager.storageclient.model.protocol.smp.StringEncrypter;
import org.gcube.contentmanager.storageclient.wrapper.AccessType;
import org.gcube.contentmanager.storageclient.wrapper.StorageClient;

public class StorageUtil {
	protected static GCUBELog logger = new GCUBELog(StorageUtil.class);
	
	public static InputStream getInputStreamByStorageClient(String url) throws Exception {
	
		logger.trace("url :" + url);
		
		String [] urlParam=url.split("\\?");
//		String param=urlParam[1];
		logger.info("String encrypted "+urlParam[1]);
		String param=new StringEncrypter("DES").decrypt(urlParam[1]);
		logger.info("String decrypted: "+param);
		String [] getParam=param.split("\\&");
		String serviceClass=null;
		String serviceName=null;
		String owner=null;
		String accessType=null;
		String scopeType=null;
		AccessType type = null;
		String server= null;
		String [] par1;
		for(String par : getParam){
			if(par.contains("ServiceClass")){
				par1=par.split("=");
				serviceClass=par1[1];
			}else if(par.contains("ServiceName")){
				par1=par.split("=");
				serviceName=par1[1];
			}else if(par.contains("owner")){
				par1=par.split("=");
				owner=par1[1];
			}else if(par.contains("scope")){
				par1=par.split("=");
				scopeType=par1[1];
			}else if(par.contains("server")){
				par1=par.split("=");
				server=par1[1];
			}else if(par.contains("AccessType")){
				par1=par.split("=");
				accessType=par1[1];			
				if(accessType.equalsIgnoreCase("public")){
					type=AccessType.PUBLIC;
				}else if(accessType.equalsIgnoreCase("shared")){
					type=AccessType.SHARED;
				}
			}else{
				;
			}
		}
		if((serviceName==null) || (serviceClass==null) || (owner == null) || (scopeType==null) || (type == null))
			throw new MalformedURLException();
		GCUBEScope scope=GCUBEScope.getScope(scopeType);
		String location=extractLocation(urlParam[0]);

		logger.trace("Storage instance with parameters "+serviceClass+" "+serviceName+" "+owner+" "+type+" "+scope+ " location: "+urlParam[0]);
		IClient client=new StorageClient(serviceClass, serviceName, owner, type, scope, server).getClient();
		InputStream is=null;
		is=client.get().RFileAStream(location);
		
//		createFileTest(is);
		return is;
	}

	public static String extractLocation(String url) {
		String [] loc=url.split("//");
		logger.trace("url extracted: "+loc[1]);
		return loc[1];
	}

}
