/*-
 * ~~~~~~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.Map;

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.Option;
import org.apache.karaf.shell.api.action.lifecycle.Service;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.base.support.JSONUtils;

@Service
@Command (scope = EntaxyProducerServiceSupport.SCOPE, name = "factory-generate")
public class FactoryGenerate extends FactoryAwareCommand implements Action {

	@Option(name = "-ot", aliases = {"--outputType"}, multiValued = false, required = false)
	String outputType;

	@Option(name = "-s", aliases = {"--scope"}, multiValued = false, required = false)
	String scope;
	
	@Argument(index = 1, name = "properties", required = false)
	String properties;
	
	@Override
	protected Object doExecute() throws Exception {
		if (!CommonUtils.isValid(properties))
			this.properties = "{}";
		
		JsonElement je = (new JsonParser()).parse(properties);
		
		Map<String, Object> propertiesMap = JSONUtils.element2map(je);
		
		Generated result = null;
		
		if (!CommonUtils.isValid(outputType))
			result = entaxyFactory.generate(propertiesMap);
		else if (!CommonUtils.isValid(scope))
			result = entaxyFactory.generate(outputType, propertiesMap);
		else
			result = entaxyFactory.generate(outputType, scope, propertiesMap);
		
		if (result == null)
			System.out.println("NOTHING GENERATED");
		else {
			System.out.println("GENERATED :: [" + result.getType() + "]");
			System.out.println("===");
			System.out.println(result.getObject()==null?"->nothing":result.getObject().toString());
			System.out.println("===");
		}
		
		return null;
	}

}
