/*-
 * ~~~~~~licensing~~~~~~
 * core-support-runtime
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.core.support.runtime.cxf;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.spi.ClassResolver;
import org.apache.camel.util.CastUtils;
import org.osgi.framework.BundleContext;
import org.osgi.framework.wiring.BundleWiring;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.platform.core.support.runtime.EntaxyResourceURLCachingClassLoader;
import ru.entaxy.platform.core.support.runtime.EntaxyResourceURLClassLoader;

public class EntaxyClassResolver implements ClassResolver, CamelContextAware {
    
    private static final Logger log = LoggerFactory.getLogger(EntaxyClassResolver.class);
    
    protected List<String> resourceFolders = new ArrayList<>();
    protected BundleContext bundleContext;
    protected boolean useCache = false;
    protected ClassLoader classLoader;
    protected ClassResolver classResolver;
    
    public EntaxyClassResolver(BundleContext bundleContext, CamelContext camelContext, List<String> resourceFolders) {
        this(bundleContext, camelContext, resourceFolders, false);
    }
    
    public EntaxyClassResolver(BundleContext bundleContext, CamelContext camelContext, List<String> resourceFolders, boolean useCache) {
        setBundleContext(bundleContext);
        setResourceFolders(resourceFolders);
        this.classLoader = createClassLoader();
        this.classResolver = camelContext.getClassResolver();
        
        camelContext.setClassResolver(this);
    }
    
    private Class<?> tryLoadClass(String name) {
        try {
            log.trace("Loading class: {} using classloader: {}", name, classLoader);
            return classLoader.loadClass(name);
        } catch (ClassNotFoundException e) {
            if (log.isTraceEnabled()) {
                log.trace("Cannot load class: " + name + " using classloader: " + classLoader, e);
            }
        }
        return null;
    }

    protected ClassLoader createClassLoader() {
        if (resourceFolders != null) {
            EntaxyResourceURLClassLoader cl = null;
            if (classLoader == null) {
                if (useCache) {
                    cl = new EntaxyResourceURLCachingClassLoader(this.bundleContext==null
                            ?this.getClass().getClassLoader()
                            :this.bundleContext.getBundle().adapt(BundleWiring.class).getClassLoader()
                    );
                    
                } else {
                    cl = new EntaxyResourceURLClassLoader(this.bundleContext==null
                                    ?this.getClass().getClassLoader()
                                    :this.bundleContext.getBundle().adapt(BundleWiring.class).getClassLoader()
                            );
                }
                cl.setResourcePath(resourceFolders);
            }
            return cl;
        }
        return null;
    }

    @Override
    public void setCamelContext(CamelContext camelContext) {
        ((CamelContextAware) classResolver).setCamelContext(camelContext);
    }

    @Override
    public CamelContext getCamelContext() {
        return ((CamelContextAware) classResolver).getCamelContext();
    }

    @Override
    public Class<?> resolveClass(String name) {
        return classResolver.resolveClass(name);
    }

    @Override
    public <T> Class<T> resolveClass(String name, Class<T> type) {
        return classResolver.resolveClass(name, type);
    }

    @Override
    public Class<?> resolveClass(String name, ClassLoader loader) {
        return classResolver.resolveClass(name, loader);
    }

    @Override
    public <T> Class<T> resolveClass(String name, Class<T> type, ClassLoader loader) {
        return classResolver.resolveClass(name, type, loader);
    }

    @Override
    public Class<?> resolveMandatoryClass(String name) throws ClassNotFoundException {
        Class<?> result = tryLoadClass(name);
        if (result == null)
            result = classResolver.resolveMandatoryClass(name);
        return result;
    }


    @Override
    public <T> Class<T> resolveMandatoryClass(String name, Class<T> type) throws ClassNotFoundException {
        Class<T> result = CastUtils.cast(tryLoadClass(name));
        if (result == null)
            result = classResolver.resolveMandatoryClass(name, type);
        return result;
    }

    @Override
    public Class<?> resolveMandatoryClass(String name, ClassLoader loader) throws ClassNotFoundException {
        Class<?> result = tryLoadClass(name);
        if (result == null)
            result = classResolver.resolveMandatoryClass(name, loader);
        return result;
    }

    @Override
    public <T> Class<T> resolveMandatoryClass(String name, Class<T> type, ClassLoader loader)
            throws ClassNotFoundException {
        Class<T> result = CastUtils.cast(tryLoadClass(name));
        if (result == null)
            result = classResolver.resolveMandatoryClass(name, type, loader);
        return result;
    }

    @Override
    public InputStream loadResourceAsStream(String uri) {
        return classResolver.loadResourceAsStream(uri);
    }

    @Override
    public URL loadResourceAsURL(String uri) {
        return classResolver.loadResourceAsURL(uri);
    }

    @Override
    public Enumeration<URL> loadResourcesAsURL(String uri) {
        return classResolver.loadResourcesAsURL(uri);
    }

    @Override
    public Enumeration<URL> loadAllResourcesAsURL(String uri) {
        return classResolver.loadAllResourcesAsURL(uri);
    }
    
    public List<String> getResourceFolders() {
        return resourceFolders;
    }

    public void setResourceFolders(List<String> resourceFolders) {
        this.resourceFolders = resourceFolders;
    }

    public BundleContext getBundleContext() {
        return bundleContext;
    }

    public void setBundleContext(BundleContext bundleContext) {
        this.bundleContext = bundleContext;
    }

    public boolean isUseCache() {
        return useCache;
    }

    public void setUseCache(boolean useCache) {
        this.useCache = useCache;
    }

}
