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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.CollectionType;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;

import ru.entaxy.platform.base.objects.factory.EntaxyFactory;
import ru.entaxy.platform.base.support.JSONUtils;
import ru.entaxy.platform.core.producer.api.EntaxyProducer;
import ru.entaxy.platform.core.producer.api.EntaxyProducerService;
import ru.entaxy.platform.core.producer.api.ProducerResult;
import ru.entaxy.platform.core.producer.api.ProducingCommandExecutor;
import ru.entaxy.platform.core.producer.executor.ProducingExecutor;
import ru.entaxy.platform.core.producer.executor.commands.Analyze;
import ru.entaxy.platform.core.producer.executor.commands.Build;
import ru.entaxy.platform.core.producer.executor.commands.Deploy;
import ru.entaxy.platform.core.producer.executor.commands.Enrich;
import ru.entaxy.platform.core.producer.executor.commands.Generate;
import ru.entaxy.platform.core.producer.executor.commands.Install;
import ru.entaxy.platform.core.producer.executor.commands.Layout;
import ru.entaxy.platform.core.producer.executor.commands.PrepareGenerate;
import ru.entaxy.platform.core.producer.executor.commands.Store;
import ru.entaxy.platform.core.producer.executor.commands.Validate;

@Component (service = {EntaxyProducerService.class}, immediate = true)
public class EntaxyProducerServiceImpl implements EntaxyProducerService {

	private static final Logger log = LoggerFactory.getLogger(EntaxyProducerServiceImpl.class);
	
	protected List<EntaxyProducer> producers = new ArrayList<>();
	
	protected Map<String, ProducingCommandExecutor> commandExecutors = new HashMap<>();
	
	@Reference (bind = "addProducer", unbind = "removeProducer", cardinality = ReferenceCardinality.MULTIPLE
			, collectionType = CollectionType.SERVICE, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY)
	public void addProducer(EntaxyProducer producer) {
		producers.add(producer);
		log.debug("Producer added: " + producer.getProducerId());
	}

	public void removeProducer(EntaxyProducer producer) {
		producers.remove(producer);
		log.debug("Producer removed: " + producer.getProducerId());
	}
	
	@Activate
	public void activate(ComponentContext componentContext) {
		registerCommand(new Analyze(this));
		registerCommand(new Layout(this));
		registerCommand(new Validate(this));
		registerCommand(new PrepareGenerate(this));
		registerCommand(new Generate(this));
		registerCommand(new Build(this));
		registerCommand(new Deploy(this));
		registerCommand(new Install(this));
		registerCommand(new Enrich(this));
		registerCommand(new Store(this));
	}
	
	@Override
	public void registerCommand(ProducingCommandExecutor commandExecutor) {
		this.commandExecutors.put(commandExecutor.getId(), commandExecutor);
	}
	
	@Override
	public ProducerResult produce(String configuration) {
		return this.produce(configuration, "{}");
	}

	@Override
	public ProducerResult produce(String configuration, String instructions) {
		return produce(JSONUtils.getJsonRootObject(configuration), instructions);
	}

	@Override
	public ProducerResult produce(JsonObject configuration) {
		return produce(configuration, "{}");
	}

	@Override
	public ProducerResult produce(JsonObject configuration, String instructions) {
		try {
			return (new ProducingExecutor(configuration, instructions,this)).execute();
		} catch (Exception e) {
			log.error("Produce failed", e);
			return ProducerResult.createFailed(e);
		}
	}
	
	
	@Override
	public List<EntaxyProducer> getAllProducers() {
		return producers;
	}

	@Override
	public EntaxyProducer getProducerForType(String type) {
		for (EntaxyProducer p: producers)
			if (p.getSupportedTypes().contains(type))
				return p;
		return null;
	}

	@Override
	public List<ProducingCommandExecutor> getAvailableCommands() {
		return new ArrayList<>(commandExecutors.values());
	}
	
	@Override
	public ProducingCommandExecutor getCommandById(String id) {
		return this.commandExecutors.get(id);
	}

	@Override
	public EntaxyFactory findFactoryById(String factoryId) {
		for (EntaxyProducer p: getAllProducers()) {
			EntaxyFactory f = p.getFactoryById(factoryId);
			if (f != null)
				return f;
		}
		return null;
	}
}
