package eu.dnetlib.data.objectstore.filesystem;

import java.io.UnsupportedEncodingException;

import com.mongodb.DBObject;
import eu.dnetlib.data.objectstore.rmi.ObjectStoreFile;
import eu.dnetlib.data.objectstore.rmi.Protocols;
import eu.dnetlib.miscutils.functional.UnaryFunction;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * The Class ObjectStoreFileBuilder generates an objectStoreFile bean
 *
 */
public class ObjectStoreFileUtility {

	private static final int KB_SIZE = 1024;

	/** The Constant log. */
	private static final Log log = LogFactory.getLog(ObjectStoreFileUtility.class);

	public static ObjectStoreFile build(final DBObject metadata, final String baseURI, final String objectStoreID, final String basePath) {

		String originalFile = (String) metadata.get("originalObject");
		ObjectStoreFile original = ObjectStoreFile.createObject(originalFile);
		ObjectStoreFile newFile = new ObjectStoreFile();
		newFile.setObjectID((String) metadata.get("id"));
		newFile.setAccessProtocol(Protocols.HTTP);
		newFile.setMimeType((String) metadata.get("mime"));
		newFile.setMd5Sum((String) metadata.get("md5Sum"));
		try {
			newFile.setFileSizeKB(Long.parseLong(metadata.get("size").toString()) / KB_SIZE);
		} catch (Throwable e) {
			log.error("Error on getting file size", e);
		}
		if (originalFile != null) {
			newFile.setMetadataRelatedID(original.getMetadataRelatedID());
			if (StringUtils.isBlank(original.getDownloadedURL())) {
				newFile.setDownloadedURL(original.getURI());
			} else {
				newFile.setDownloadedURL(original.getDownloadedURL());
			}
		}
		try {
			newFile.setURI(ModularObjectStoreRESTService.retrieveURL(baseURI, basePath, objectStoreID, newFile.getObjectID()));
		} catch (UnsupportedEncodingException e) {
			log.error("Error on Build objectStoreFile ", e);
		}
		return newFile;
	}

	public static UnaryFunction<String, DBObject> asJSON(final String baseURI, final String objectStoreID, final String basePath) {
		return input -> build(input, baseURI, objectStoreID, basePath).toJSON();
	}
}
