package org.opencds.cqf.r4.providers;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Objects;

import org.hl7.elm.r1.VersionedIdentifier;
import org.hl7.fhir.r4.model.*;

public class R4BundleLibrarySourceProvider extends VersionComparingLibrarySourceProvider  {

    Bundle bundle;
    public R4BundleLibrarySourceProvider(Bundle bundle) {
        this.bundle = bundle;
    }

    @Override
    public InputStream getLibrarySource(VersionedIdentifier versionedIdentifier) {
        Objects.requireNonNull(versionedIdentifier, "versionedIdentifier can not be null.");
        
        Library library = this.getLibrary(versionedIdentifier.getId(), versionedIdentifier.getVersion());
        if (library == null ){
            return null;
        }

        return this.getCqlStream(library);
    }

    public Library getLibrary(String name, String version) {
        // TODO: Check the bundle

        return null;
    }

    private InputStream getCqlStream(Library library) {
        if (library.hasContent()) {
            for (Attachment content : library.getContent()) {
                // TODO: Could use this for any content type, would require a mapping from content type to LanguageServer LanguageId
                if (content.getContentType().equals("text/cql")) {
                    return new ByteArrayInputStream(content.getData());
                }
                // TODO: Decompile ELM if no CQL is available?
            }
        }

        return null;
    }
}
@@ -122,16 +122,43 @@
 Objects;
+%0Aimport java.util.Optional;
 %0A%0Aimport
@@ -225,16 +225,183 @@
 model.*;
+%0Aimport org.opencds.cqf.cql.engine.fhir.model.FhirModelResolver;%0Aimport org.opencds.cqf.cql.engine.fhir.model.R4FhirModelResolver;%0A%0Aimport ca.uhn.fhir.util.BundleUtil;
 %0A%0Apublic
@@ -1096,49 +1096,391 @@
     
-// TODO: Check the bundle%0A%0A        return
+FhirModelResolver resolver = new R4FhirModelResolver();%0A        Optional%3CLibrary%3E result = BundleUtil.toListOfResourcesOfType(resolver.getFhirContext(), this.bundle, Library.class)%0A            .stream()%0A            .filter(library -%3E library.getName().equals(name) && library.getVersion().equals(version))%0A            .findFirst();%0A%0A        return result.isPresent() ? result.get() :
  nul

Add getting the library from the bundle