001package org.intellimate.izou.sdk.util;
002
003import org.intellimate.izou.identification.Identifiable;
004import org.intellimate.izou.identification.Identification;
005import org.intellimate.izou.identification.IdentificationManager;
006import org.intellimate.izou.identification.IllegalIDException;
007import org.intellimate.izou.resource.ResourceModel;
008import org.intellimate.izou.sdk.resource.Resource;
009
010import java.util.List;
011import java.util.Optional;
012import java.util.concurrent.CompletableFuture;
013
014/**
015 * provides various utility-methods to receive Resources
016 * @author Leander Kurscheidt
017 * @version 1.0
018 */
019//TODO: Leander the return type optional is really unnecessary, i don't think the information resulting from it is
020// useful. We should implement the tip and return CompletableFuture and log if there was an error obtaining the ID.
021// The question is whether to archive this without breaking backwards compatibility (might turn really ugly and i like
022// the current method name)
023public interface ResourceUser extends ContextProvider, Identifiable {
024    /**
025     * generates the specified resource from the first matching ResourceBuilder (use the ID if you want to be sure).
026     * tip: for a better coding experience: use the method
027     * <pre>{@code
028     * .orElse(CompletableFuture.completedFuture(new LinkedList<>()))
029     * }</pre>
030     * to handle the empty case.
031     * @param resourceID the id of the resource
032     * @return an Optional containing a future of a list of results
033     */
034    default Optional<CompletableFuture<List<ResourceModel>>> generateResource(String resourceID) {
035        return generateResource(resourceID, null);
036    }
037
038    /**
039     * generates the specified resource from the specified ResourceBuilder.
040     * tip: for a better coding experience: use the method
041     * <pre>{@code
042     * .orElse(CompletableFuture.completedFuture(new LinkedList<>()))
043     * }</pre>
044     * to handle the empty case.
045     * @param resourceID the id of the resource
046     * @param provider the specified provider
047     * @return an Optional containing a future of a list of results
048     */
049    default Optional<CompletableFuture<List<ResourceModel>>> generateResource(String resourceID, Identification provider) {
050        return IdentificationManager.getInstance()
051                .getIdentification(this)
052                .map(id -> new Resource(resourceID, provider, id))
053                .flatMap(resource -> {
054                    try {
055                        return getContext().getResources().generateResource(resource);
056                    } catch (IllegalIDException e) {
057                        getContext().getLogger().error("unable to generate Resource", e);
058                        return Optional.empty();
059                    }
060                });
061    }
062}