/*-
 * ~~~~~~licensing~~~~~~
 * object-producing-management
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.core.producer.management.impl;

import java.util.Collections;
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.objects.factory.exceptions.NotSupportedForAbstractFactory;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.base.support.JSONUtils;
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 boolean isAbstract() {
		return this.entaxyFactory.isAbstract();
	}

	@Override
	public boolean isInternal() {
		return this.entaxyFactory.isInternal();
	}

	@Override
	public boolean isDeprecated() {
		return this.entaxyFactory.isDeprecated();
	}
	
	@Override
	public String getId() {
		return this.entaxyFactory.getId();
	}

	@Override
	public String getType() {
		return this.entaxyFactory.getType();
	}

	@Override
	public String getParent() {
		return this.entaxyFactory.getParent();
	}

	@Override
	public String getShortName() {
		String shortName = this.entaxyFactory.getShortName();
		if (CommonUtils.isValid(shortName)) {
			return shortName;
		}
		return this.entaxyFactory.getId();
	}

	@Override
	public String getDisplayName() {
		return this.entaxyFactory.getDisplayName();
	}
	
	@Override
	public String getDescription() {
		return this.entaxyFactory.getDescription();
	}

	@Override
	public String getCategory() {
		return this.entaxyFactory.getCategory();
	}

	@Override
	public String getLabel() {
		return this.entaxyFactory.getLabel();
	}
	
	@Override
	public Map<String, Object> getTypeInfo() {
		return this.entaxyFactory.getTypeInfo();
	}
	
	@Override
	public TabularData createObject(String objectId, String scope, Map<String, Object> properties) throws EntaxyFactoryException, OpenDataException {
		return createObjectByInstructions(objectId, scope, Collections.emptyMap(), properties);
	}
	
	@Override
	public TabularData createObjectByInstructions(String objectId, String scope, Map<String, Object> instructions, Map<String, Object> properties) throws EntaxyFactoryException, OpenDataException {
		
		if (this.isAbstract()) {
			throw new NotSupportedForAbstractFactory(entaxyFactory, "createObject");
		}
		
		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);
		
		String instructionsString = "{\"install\": {}, \"store\":{}}";
		if ((instructions != null) && !instructions.isEmpty()) {
			JsonElement jo = (new Gson()).toJsonTree(instructions);
			if (jo.isJsonObject())
				instructionsString = jo.toString();
		}
		
		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 = JSONUtils.GSON.toJsonTree(properties);
		configuration.add(EntaxyObject.FIELDS.PROPERTIES, propertiesValue);
		
		ProducerResult result = producerService.produce(configuration, instructionsString);
		
		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();
	}


}
