/*
 * Copyright (c) 2021, 2023 Oracle and/or its affiliates. All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0, which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * This Source Code may also be made available under the following Secondary
 * Licenses when the conditions for such availability set forth in the
 * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
 * version 2 with the GNU Classpath Exception, which is available at
 * https://www.gnu.org/software/classpath/license.html.
 *
 * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
 */

package jakarta.mail.util;

import java.util.Arrays;
import java.util.Iterator;
import java.util.ServiceLoader;

class FactoryFinder {

    /**
     * Finds the implementation {@code Class} object for the given
     * factory type.
     * The arguments supplied must be used in order
     * This method is package private so that this code can be shared.
     *
     * @param factoryClass factory abstract class or interface to be found
     * @return the {@code Class} object of the specified message factory
     * @throws RuntimeException if there is an error
     */
    static <T> T find(Class<T> factoryClass) throws RuntimeException {
        T result;
        ClassLoader loader = factoryClass.getClassLoader();
        if (loader != null) {
            result = find(factoryClass, loader);
            if (result != null) {
                return result;
            }
        }
        result = find(factoryClass, ClassLoader.getSystemClassLoader());
        if (result != null) {
            return result;
        }

        throw new IllegalStateException("No provider of " + factoryClass.getName() + " was found");
    }

    private static <T> T find(Class<T> factoryClass, ClassLoader loader) throws RuntimeException {
        // Use the system property first
        String className = fromSystemProperty(factoryClass.getName());
        if (className != null) {
            T result = newInstance(className, factoryClass, loader);
            if (result != null) {
                return result;
            }
        }

        // standard services: java.util.ServiceLoader
        return factoryFromServiceLoader(factoryClass, loader);
    }

    private static <T> T newInstance(String className, Class<T> factoryClass, ClassLoader classLoader) throws RuntimeException {
        try {
            Class<?> clazz;
            if (classLoader == null) { //Match behavior of ServiceLoader
                classLoader = ClassLoader.getSystemClassLoader();
            }
            clazz = Class.forName(className, false, classLoader);
            return clazz.asSubclass(factoryClass).getConstructor().newInstance();
        } catch (ClassCastException wrongLoader) {
            return null;
        } catch (ReflectiveOperationException e) {
            throw new IllegalArgumentException("Cannot instance " + className, e);
        }
    }

    private static String fromSystemProperty(String factoryId) {
        return System.getProperty(factoryId);
    }

    private static <T> T factoryFromServiceLoader(Class<T> factory, ClassLoader loader) {
        try {
            ServiceLoader<T> sl = ServiceLoader.load(factory, loader);
            Iterator<T> iter = sl.iterator();
            if (iter.hasNext()) {
                return factory.cast(iter.next()); //Verify loader
            } else {
                return null;
            }
        } catch (ClassCastException wrongLoader) {
            return null;
        } catch (Throwable t) {
            throw new IllegalStateException("Cannot load " + factory + " as ServiceLoader", t);
        }
    }
}

