/*-
 * ~~~~~~licensing~~~~~~
 * object-runtime-core
 * ==========
 * 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.objects.runtime.impl.manager;

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

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

import ru.entaxy.platform.base.objects.EntaxyObject;
import ru.entaxy.platform.base.objects.EntaxyObject.OBJECT_RELATION;
import ru.entaxy.platform.core.artifact.legacy.BundleController;
import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject;
import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject.ENTAXY_RUNTIME_OBJECT_STATE;
import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectManager.ENTAXY_RUNTIME_OBJECT_OPERATION;
import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectManager.ENTAXY_RUNTIME_OBJECT_OPERATION_RESULT;
import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectManager.OperationConfig;
import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectManager.OperationResult;
import ru.entaxy.platform.objects.runtime.EntaxyRuntimeRelation;
import ru.entaxy.platform.objects.runtime.impl.EntaxyRuntimeObjectServiceImpl;

public class OperationExecutorStop extends OperationExecutor<OperationExecutorStop> {

	private static final Logger log = LoggerFactory.getLogger(OperationExecutorStop.class);
	
	@Override
	protected Map<String, ENTAXY_RUNTIME_OBJECT_OPERATION> doGetAffected(OperationConfig operationConfig,
			EntaxyRuntimeObject runtimeObject) {
		final Map<String, ENTAXY_RUNTIME_OBJECT_OPERATION> result = new HashMap<>();

		List<EntaxyRuntimeRelation> relations = runtimeObject.getRelations(OBJECT_RELATION.AGGREGATION);
		relations.addAll(runtimeObject.getIncomiingRelations(OBJECT_RELATION.DEPENDENCY));
		relations.addAll(runtimeObject.getIncomiingRelations(OBJECT_RELATION.USE));
		
		List<EntaxyRuntimeObject> objects = relations.stream()
				.map(rel -> rel.getDependent())
				.filter(obj ->
						!runtimeObject.isColocatedWith(obj) ||
								!EntaxyObject.OBJECT_SCOPE.PRIVATE.equals(obj.getScope()))
				.filter(obj -> ENTAXY_RUNTIME_OBJECT_STATE.ACTIVE.equals(getObjectState(obj)))
				.collect(Collectors.toList());
		
		for (EntaxyRuntimeObject obj: objects)
			result.put(obj.getObjectFullId(), ENTAXY_RUNTIME_OBJECT_OPERATION.STOP);
		
		return result;
	}
	
	@Override
	protected OperationResultImpl doExecute(OperationConfig operationConfig, EntaxyRuntimeObject runtimeObject) {
		// stop all compostion-dependent objects, not colocated with the current
		List<EntaxyRuntimeObject> parts = runtimeObject.getRelations(OBJECT_RELATION.COMPOSITION).stream()
				.map(rel -> rel.getDependent())
				.filter(obj -> !runtimeObject.getContainer().getId().equals(obj.getContainer().getId()))
				.collect(Collectors.toList());
		
		for (EntaxyRuntimeObject part: parts) {
			OperationResult result = objectManager.stopForced(part.getObjectFullId());
			if (ENTAXY_RUNTIME_OBJECT_OPERATION_RESULT.FAILED.equals(result.getResult()))
				return OperationResultImpl.createFailed().message(
						"FAILED stopping [" + part.getObjectFullId() + "]; ORIGINAL MESSAGE: " + result.getMessage());
		}
		
		// stop all affected objects
		for (String affectedId: operationConfig.getAffected().keySet()) {
			// EntaxyRuntimeObject affected = objectManager.getObjectService().getRuntimeObject(affectedId);
			OperationResult result = objectManager.stopForced(affectedId);
			if (ENTAXY_RUNTIME_OBJECT_OPERATION_RESULT.FAILED.equals(result.getResult()))
				return OperationResultImpl.createFailed().message(
						"FAILED stopping [" + affectedId + "]; ORIGINAL MESSAGE: " + result.getMessage());
		}
		
		try {
			getBundleController(runtimeObject).stopBundle(runtimeObject.getContainer().getName());
			return OperationResultImpl.createDone();
		} catch (Exception e) {
			log.error("ERROR stoping [" + runtimeObject.getObjectFullId() + "]", e);
			return OperationResultImpl.createFailed().message("ERROR stoping [" + runtimeObject.getObjectFullId() 
				+ "]; ORIGINAL MESSAGE: " + e.getMessage());
		}
		

	}

}
