/*-
 * ~~~~~~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 java.util.ArrayList;
import java.util.List;

import org.apache.karaf.shell.api.action.Action;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.apache.karaf.shell.support.table.Col;
import org.apache.karaf.shell.support.table.ShellTable;

import ru.entaxy.platform.base.objects.factory.EntaxyFactory;
import ru.entaxy.platform.core.producer.api.EntaxyProducer;

@Service
@Command (scope = "producer", name = "factory-list")
public class ListFactories extends EntaxyProducerServiceSupport implements Action {

	@Argument (index = 0, multiValued = false, required = false)
	String targetType;
	
	@Override
	public Object execute() throws Exception {
		List<EntaxyProducer> producers = new ArrayList<>();
		if (null != targetType) {
			EntaxyProducer producer = producerService.getProducerForType(targetType);
			if (producer != null)
				producers.add(producer);
		} else {
			producers.addAll(producerService.getAllProducers());
		}
		
		ShellTable table = new ShellTable();
		table.column("Id");
		table.column("Type");
		table.column("Category");
		table.column("Label");

		Col descriptionColumn = new Col("Description")
				.maxSize(40).wrap(true);
		
		table.column(descriptionColumn);
				
		
		for (EntaxyProducer p: producers) {
			List<EntaxyFactory> factories = targetType==null?p.getAllFactories():p.getFactoriesForType(targetType);
			for (EntaxyFactory factory: factories) {
				table.addRow().addContent(
						factory.getId(), factory.getType()
						, factory.getCategory(), factory.getLabel()
						, factory.getDescription());
			}
		}
		
		table.print(System.out);
		return null;
	}
	
}
