/*-
 * ~~~~~~licensing~~~~~~
 * artifact-management
 * ==========
 * 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.platform.core.artifact;

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;

import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated;
import ru.entaxy.platform.core.artifact.annotation.ArtifactSupport;

public class Artifacts {

	private static final Logger log = LoggerFactory.getLogger(Artifacts.class);
	
	protected static final Map<String, Class<?>> supportClasses = new HashMap<>();

	static {
		Artifacts.registerSupport(Blueprint.class);
	}
	
	
	public static final void registerSupport(Class<?> supportClass) {
		if (supportClass.isAnnotationPresent(ArtifactSupport.class)) {
			String artifactType = supportClass.getAnnotation(ArtifactSupport.class).supportedCategory();
			Artifacts.supportClasses.put(artifactType, supportClass);
		}
	}
	
	public static final DefaultArtifact create(String category) {
		if (supportClasses.containsKey(category)) {
			Class<?> supportClass = supportClasses.get(category);
			try {
				Constructor<?> c = supportClass.getConstructor();
				Object instance = c.newInstance();
				if (DefaultArtifact.class.isAssignableFrom(instance.getClass()))
					return (DefaultArtifact)instance;
			} catch (NoSuchMethodException e) {
				log.error("Error creating artifact", e);
			} catch (SecurityException e) {
				log.error("Error creating artifact", e);
			} catch (InstantiationException e) {
				log.error("Error creating artifact", e);
			} catch (IllegalAccessException e) {
				log.error("Error creating artifact", e);
			} catch (IllegalArgumentException e) {
				log.error("Error creating artifact", e);
			} catch (InvocationTargetException e) {
				log.error("Error creating artifact", e);
			}
		}
		return new DefaultArtifact(); 
	}
	
	public static final DefaultArtifact fromGenerated(Generated generated) {
		DefaultArtifact result = Artifacts.create(generated.getType());
		if (result != null)
			result.setContent(generated.getObject());
		return result;
	}
	
}
