package io.hawt.jsonschema;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
import io.hawt.util.MBeanSupport;
import io.hawt.jsonschema.internal.BeanValidationAnnotationModule;
import io.hawt.jsonschema.internal.IgnorePropertiesBackedByTransientFields;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;

/**
 * @author Stan Lewis
 */
public class SchemaLookup extends MBeanSupport implements SchemaLookupMXBean {
    private static final transient Logger LOG = LoggerFactory.getLogger(SchemaLookup.class);

    private static SchemaLookup singleton;

    private ObjectMapper mapper;

    public SchemaLookup() {
    }

    public static SchemaLookup getSingleton() {
        if (singleton == null) {
            // lazy create one
            new SchemaLookup().init();
        }
        return singleton;
    }

    public void init() {
        LOG.debug("Creating hawtio SchemaLookup instance");
        try {
            if (mapper == null) {
                mapper = new ObjectMapper();

                mapper.setVisibilityChecker(new IgnorePropertiesBackedByTransientFields(mapper.getVisibilityChecker()));

                JaxbAnnotationModule module1 = new JaxbAnnotationModule();
                mapper.registerModule(module1);

                BeanValidationAnnotationModule module2 = new BeanValidationAnnotationModule();
                mapper.registerModule(module2);

            }
            // now lets expose the mbean...
            super.init();
            singleton = this;
        } catch (Exception e) {
            LOG.warn("Exception during initialization: ", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    protected String getDefaultObjectName() {
        return "io.hawt.jsonschema:type=SchemaLookup";
    }

    protected Class getClass(String name) {
        Bundle[] bundles = FrameworkUtil.getBundle(getClass()).getBundleContext().getBundles();
        for (Bundle bundle : bundles) {
            if (bundle.getState() >= Bundle.RESOLVED) {
                try {
                    return bundle.loadClass(name);
                } catch (ClassNotFoundException e) {
                    // Ignore
                }
            }
        }
        LOG.warn("Failed to find class for {}", name);
        ClassNotFoundException e = new ClassNotFoundException(name);
        throw new RuntimeException(new ClassNotFoundException(name));
    }

    @Override
    public String getSchemaForClass(String name) {
        Class clazz = getClass(name);
        return getSchemaForClass(clazz);
    }

    public String getSchemaForClass(Class clazz) {
        LOG.info("Looking up schema for " + clazz.getCanonicalName());
        String name = clazz.getName();
        try {
            ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
            return writer.writeValueAsString(mapper.generateJsonSchema(clazz));
        } catch (Exception e) {
            LOG.warn("Failed to generate JSON schema for class {}", name, e);
            throw new RuntimeException(e);
        }
    }

    public ObjectMapper getMapper() {
        return mapper;
    }

    public void setMapper(ObjectMapper mapper) {
        this.mapper = mapper;
    }
}

@@ -396,24 +396,65 @@
 ork.Bundle;%0A
+import org.osgi.framework.BundleContext;%0A
 import org.o
@@ -2248,75 +2248,296 @@
 ndle
-%5B%5D bundles = FrameworkUtil.getBundle(getClass()).getBundleContext()
+Context bundleContext = null;%0A        Bundle currentBundle = FrameworkUtil.getBundle(getClass());%0A        if (currentBundle != null) %7B%0A            bundleContext = currentBundle.getBundleContext();%0A        %7D%0A        if (bundleContext != null) %7B%0A            Bundle%5B%5D bundles = bundleContext
 .get
@@ -2543,24 +2543,28 @@
 tBundles();%0A
+    
         for 
@@ -2595,32 +2595,36 @@
 ) %7B%0A            
+    
 if (bundle.getSt
@@ -2647,24 +2647,28 @@
 RESOLVED) %7B%0A
+    
             
@@ -2693,24 +2693,28 @@
             
+    
 return bundl
@@ -2724,32 +2724,36 @@
 oadClass(name);%0A
+    
                 
@@ -2809,16 +2809,20 @@
         
+    
 // Ignor
@@ -2831,33 +2831,307 @@
                 
-%7D
+    %7D%0A                %7D%0A            %7D%0A        %7D else %7B%0A            try %7B%0A                return Class.forName(name);%0A            %7D catch (ClassNotFoundException e) %7B%0A                LOG.warn(%22Failed to find class for %7B%7D%22, name);%0A                throw new RuntimeException(e);
 %0A            %7D%0A 

fix SchemaLookup when not inside OSGi so we don't have a Bundle/BundleContext ##735