/*-
 * ~~~~~~licensing~~~~~~
 * object-producing-management
 * ==========
 * 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.management.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import javax.management.NotCompliantMBeanException;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import ru.entaxy.esb.platform.base.management.core.api.AnnotatedMBean;
import ru.entaxy.platform.base.objects.EntaxyObject;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory.SCOPE;
import ru.entaxy.platform.base.objects.factory.EntaxyFactoryException;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.core.producer.api.EntaxyProducerService;
import ru.entaxy.platform.core.producer.api.ProducerResult;
import ru.entaxy.platform.core.producer.api.ProducerResult.CommandResult;
import ru.entaxy.platform.core.producer.management.FactoryMBean;

public class FactoryMBeanImpl extends AnnotatedMBean<FactoryMBean> implements FactoryMBean {

	private static final Logger log = LoggerFactory.getLogger(FactoryMBeanImpl.class);
	
	protected EntaxyFactory entaxyFactory;
	
	public FactoryMBeanImpl(EntaxyFactory entaxyFactory) throws NotCompliantMBeanException {
		super(FactoryMBean.class);
		this.entaxyFactory = entaxyFactory;
	}

	@Override
	public TabularData createObject(String objectId, String scope, Map<String, Object> properties) throws EntaxyFactoryException, OpenDataException {
		log.debug("\n\tCREATE OBJECT with \nid: [{}] \nscope: [{}] \nproperties: [{}]"
				, CommonUtils.getValid(objectId, "null")
				, CommonUtils.getValid(scope, SCOPE.PUBLIC.label)
				, properties==null?"{}":properties.toString());
		
		EntaxyProducerService producerService = ProducerServiceHelper.getInstance().producerService;
		
		String targetScope = CommonUtils.getValid(scope, SCOPE.PUBLIC.label);
		if (SCOPE.valueOfLabel(targetScope)==null)
			targetScope = SCOPE.PUBLIC.label;
		
		JsonObject configuration = new JsonObject();
		if (CommonUtils.isValid(objectId))
			configuration.addProperty(EntaxyObject.FIELDS.OBJECT_ID, objectId);
		
		configuration.addProperty(EntaxyObject.FIELDS.FACTORY_ID, this.entaxyFactory.getFactoryId());
		configuration.addProperty(EntaxyObject.FIELDS.OBJECT_TYPE, this.entaxyFactory.getFactoryType());
		
		configuration.addProperty(EntaxyObject.FIELDS.SCOPE, targetScope);
		
		JsonElement propertiesValue = (new Gson()).toJsonTree(properties);
		configuration.add(EntaxyObject.FIELDS.PROPERTIES, propertiesValue);
		
		ProducerResult result = producerService.produce(configuration, "{\"install\": {}, \"store\":{}}");
		
		CompositeType compositeType = new CompositeType(
				"CommandResult"
				, "CommandResult"
				, new String[] {"Step", "Step name", "Step result"}
				, new String[] {"Step", "Step name", "Step result"}
				, new OpenType[] {SimpleType.INTEGER, SimpleType.STRING, SimpleType.STRING});
		TabularType tabularType = new TabularType("ProducerResult"
				, "ProducerResult"
				, compositeType
				, new String[] {"Step"});
		TabularDataSupport dataSupport = new TabularDataSupport(tabularType);
		
		int number = 0;
		for (CommandResult cr: result.getCommandResults()) {
			Map<String, Object> data = new HashMap<>();
			data.put("Step", number++);
			data.put("Step name", cr.commandId);
			data.put("Step result", cr.result?"OK":"Failed");
			CompositeDataSupport cds = new CompositeDataSupport(compositeType, data);
			dataSupport.put(cds);
		}
		
		return dataSupport;
		
	}

	@Override
	public String getFields(String outputType) {
		return entaxyFactory.getFields(outputType)
				.stream().map(fieldInfo -> {
					JsonObject json = fieldInfo.getJsonOrigin();
					if (!json.has("name")) {
						json.addProperty("name", fieldInfo.getName());
					}
					return json;
				}).collect(Collectors.toList()).toString();
	}

}
