package org.gcube.application.geoportal.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.gcube.application.geoportal.common.faults.StorageException;
import org.gcube.application.geoportal.common.model.rest.TempFile;
import org.gcube.application.geoportal.common.rest.InterfaceConstants;
import org.gcube.contentmanagement.blobstorage.service.IClient;
import org.gcube.contentmanagement.blobstorage.transport.backend.RemoteBackendException;
import org.gcube.contentmanager.storageclient.wrapper.AccessType;
import org.gcube.contentmanager.storageclient.wrapper.MemoryType;
import org.gcube.contentmanager.storageclient.wrapper.StorageClient;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;

@Slf4j
public class StorageUtils {

	private static final IClient getClient(){
		return new StorageClient(InterfaceConstants.SERVICE_CLASS, InterfaceConstants.SERVICE_NAME,
				ContextUtils.getCurrentCaller(), AccessType.SHARED, MemoryType.VOLATILE).getClient();
	}
	
	private IClient client;
	public StorageUtils() {
		client=getClient();
	}

	public void forceClose(){
//		client.forceClose();
	}

	public TempFile putOntoStorage(InputStream source,String filename) throws RemoteBackendException, FileNotFoundException{		
		log.debug("Uploading source "+filename);
		String id=client.put(true).LFile(source).RFile(getUniqueString());
		return new TempFile(id,null,filename);
	}


	public TempFile putOntoStorage(File source, String filename) throws RemoteBackendException, FileNotFoundException{
		if(source.exists() && source.canRead())
			return putOntoStorage(new FileInputStream(source),filename);
		else throw new FileNotFoundException("Unable to read "+source.getAbsolutePath()+" ("+filename+")");
	}

	public TempFile[] putOntoStorage(File... source) throws RemoteBackendException, FileNotFoundException{
		TempFile[] toReturn=new TempFile[source.length];
		for (int i = 0; i < source.length; i++) {
			toReturn[i]=putOntoStorage(source[i],source[i].getName());
		}
		return toReturn;
	}


	public TempFile putOntoStorage(String sourcePath, String filename) throws RemoteBackendException, FileNotFoundException{
		return putOntoStorage(new File(sourcePath),filename);
	}


	public void removeById(String id){
		this.client.remove().RFile(id);
	}

	public String getURL(String id){
		return this.client.getHttpsUrl().RFile(id);
	}
	public void exists(String id){
		this.client.exist().RFile(id);
	}

	public static final String getUniqueString(){
		return UUID.randomUUID().toString();
	}

	public File download(String id,String name) throws IOException, StorageException {
			Path p = Files.createTempDirectory(id).resolve(name);

			client.get().LFile(p.toAbsolutePath().toString()).RFile(id);
			File toReturn =p.toFile();
			if(!toReturn.exists()) throw new StorageException("Unable to download "+id);
			return p.toFile();
	}
}
