/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.cryptolib.commons.concurrent;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import com.scytl.cryptolib.api.exceptions.CryptoLibException;
import com.scytl.cryptolib.api.services.ServiceFactory;

/**
 * This class helps to set up default factories of the desired objects.
 */
public final class ServiceFactoryHelper {

    /**
     * This is a helper class. It cannot be instantiated.
     */
    private ServiceFactoryHelper() {
    }

    /**
     * Creates an instance of the given Class by invoking the constructor with
     * the given parameters.
     * 
     * @param clazz
     *            Class type.
     * @param params
     *            Needed parameters.
     * @return The created factory.
     */
    @SuppressWarnings({"rawtypes", "unchecked" })
    public static ServiceFactory get(final Class clazz,
            final Object... params) {

        List<Class> list = new ArrayList<>();

        for (Object object : params) {
            list.add(object.getClass());
        }
        Class[] paramTypes = list.toArray(new Class[params.length]);
        Object instance;

        try {
            if (params.length == 0) {
                instance = clazz.newInstance();
            } else {
                instance =
                    clazz.getConstructor(paramTypes).newInstance(params);
            }
        } catch (InstantiationException | IllegalAccessException
                | IllegalArgumentException | InvocationTargetException
                | NoSuchMethodException | SecurityException e) {
            throw new CryptoLibException(e);
        }
        return (ServiceFactory) instance;
    }
}
