/*-
 * ~~~~~~licensing~~~~~~
 * generator-api
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.platform.runtime.base.connecting.generator;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractSelfPublishGenerator<T extends AbstractSelfPublishGenerator<T>> implements Generator, GeneratorService {

	private static final Logger log = LoggerFactory.getLogger(AbstractSelfPublishGenerator.class);
	
	protected Map<String, Object> initialProperties = new HashMap<>();
	
	@Override
	public Generator getGenerator(Map<String, Object> initialProperties) {
		String errorClass = "CLASS=[" + this.getClass().getName() + "]";
		try {
			Constructor<T> constructor = ((Class<T>)this.getClass()).getConstructor();
			T instance = constructor.newInstance();
			instance.init(initialProperties);
			return (Generator) instance;
		} catch (NoSuchMethodException | SecurityException e) {
			log.error(errorClass, e);
		} catch (InstantiationException e) {
			log.error(errorClass, e);
		} catch (IllegalAccessException e) {
			log.error(errorClass, e);
		} catch (IllegalArgumentException e) {
			log.error(errorClass, e);
		} catch (InvocationTargetException e) {
			log.error(errorClass, e);
		}
		return null;
	}

	@Override
	public String getGeneratorId() {
		return this.getClass().getName();
	}
	
	protected void init(Map<String, Object> initialProperties) {
		this.initialProperties.putAll(initialProperties);
	}
	
}
