/*-
 * ~~~~~~licensing~~~~~~
 * test-producers
 * ==========
 * Copyright (C) 2020 - 2022 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.producer.shell;

import org.apache.karaf.shell.api.action.Action;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Completion;
import org.apache.karaf.shell.api.action.Option;

import ru.entaxy.platform.base.objects.factory.EntaxyFactory;
import ru.entaxy.platform.core.producer.api.EntaxyProducer;
import ru.entaxy.platform.core.producer.api.EntaxyWrappedFactory;
import ru.entaxy.platform.core.producer.shell.completers.FactoryIdCompleter;

public abstract class FactoryAwareCommand extends EntaxyProducerServiceSupport implements Action {

	@Argument (index = 0, name = "factoryId", required = true)
	@Completion(caseSensitive = false, value = FactoryIdCompleter.class)
	String factoryId;
	
	@Option(name = "-r", aliases = {"--use-origin"}, multiValued = false, required = false)
	boolean useOrigin;
	
	protected EntaxyFactory entaxyFactory;
	
	@Override
	public final Object execute() throws Exception {
		for (EntaxyProducer p: producerService.getAllProducers()) {
			entaxyFactory = p.getFactoryById(factoryId);
			if (entaxyFactory != null)
				break;
		}
		
		if (entaxyFactory == null)
			System.out.println("Factory [" + factoryId + "] not found");
		else {
			if (useOrigin)
				if (entaxyFactory instanceof EntaxyWrappedFactory)
					entaxyFactory = ((EntaxyWrappedFactory)entaxyFactory).getOrigin();
			return doExecute();
		}
		return null;
	}
	
	protected abstract Object doExecute()  throws Exception;
	
}
