/*
 * 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 com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;

/**
 * This abstract class configures the factory with a properties file.
 * 
 * @param <T>
 *            This parameter sets the class of objects that this factory is
 *            going to create.
 */
public class PropertiesConfiguredFactory<T> extends BaseFactory<T> {

    private static final String UNSUPPORTED_OPERATION_EXCEPTION_MESSAGE =
        "this method should be implemented by child implementations";

    protected final String _path;

    /**
     * Creates an instance of factory what will create objects of specified
     * {@code objectType}. This factory will create services configured with
     * default values.
     *
     * @param objectType
     *            Interface of the objects created by this factory.
     */
    protected PropertiesConfiguredFactory(final Class<T> objectType) {
        super(objectType);
        _path = null;
    }

    /**
     * This factory will create services configured with the given properties
     * file.
     * 
     * @param objectType
     *            the object type
     * @param path
     *            The path of the properties file to be used to configure the
     *            service.
     */
    protected PropertiesConfiguredFactory(final Class<T> objectType,
            final String path) {
        super(objectType);
        _path = path;
    }

    @Override
    public T create() throws GeneralCryptoLibException {
        if (isBlank(_path)) {
            return createObjectUsingDefaultPath();
        } else {
            return createObjectWithPath();
        }
    }

    protected T createObjectUsingDefaultPath()
            throws GeneralCryptoLibException {
        throw new GeneralCryptoLibException(
            UNSUPPORTED_OPERATION_EXCEPTION_MESSAGE);
    }

    protected T createObjectWithPath() throws GeneralCryptoLibException {
        throw new GeneralCryptoLibException(
            UNSUPPORTED_OPERATION_EXCEPTION_MESSAGE);
    }

    private static boolean isBlank(String value) {
        if (value == null) {
            return true;
        }
        for (int i = 0; i < value.length(); i++) {
            if (!Character.isWhitespace(value.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}
