/*-
 * ~~~~~~licensing~~~~~~
 * test-producers
 * ==========
 * 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.executor.generationmodel;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

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

import ru.entaxy.platform.base.objects.EntaxyObject;
import ru.entaxy.platform.base.objects.EntaxyObject.FIELDS;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory;
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.executor.objectmodel.FactoredObject;
import ru.entaxy.platform.core.producer.executor.objectmodel.FactoredObjectProxy;
import ru.entaxy.platform.core.producer.executor.objectmodel.FactoredObjectRef;

public class GenerateRefTask extends AbstractRefTask {

	protected GenerateRefTask(FactoredObjectRef objectRef) {
		super(objectRef);
	}

	@Override
	public String getInfo() {
		return "GENERATE-REF " + "[" + objectRef.getTargetId() + "] :: " + objectRef.factoryId;
	}

	@Override
	public boolean execute(ProducerResult currentResult, CommandResult currentCommand,
			EntaxyProducerService producerService, Map<String, Object> instructions) throws Exception {
		FactoredObject targetObject = this.objectRef.getTargetObject();
		if (targetObject != null) {
			if (targetObject instanceof FactoredObjectProxy) {
				 EntaxyObject target = ObjectResolveHelper.getInstance().findObject(
						 this.objectRef.getTargetId(), 
						 this.objectRef.getTargetType());
				 if (target == null)
					 throw new IllegalArgumentException("Object not found: ["
							+ this.objectRef.getTargetId()
							+ ":"
							+ this.objectRef.getTargetType()
					 		+ "]");
				 JsonObject targetConfig = JSONUtils.getJsonRootObject(target.getConfiguration()).deepCopy();
				 JsonObject currentConfig = this.objectRef.origin;
				 JSONUtils.mergeObjects(currentConfig, targetConfig);
			
				 // System.out.println("\n\n\tGENERATING REF WITH CONFIG: \n\t" + targetConfig);
				 
				 String factoryId = targetConfig.has(FIELDS.FACTORY_ID)
						 ?targetConfig.get(FIELDS.FACTORY_ID).getAsString()
						 :"";

				 String factoryType = targetConfig.has(FIELDS.OBJECT_TYPE)
						 ?targetConfig.get(FIELDS.OBJECT_TYPE).getAsString()
						 :"";
				 
				 if (!CommonUtils.isValid(factoryId) || !CommonUtils.isValid(factoryType))
					 throw new IllegalArgumentException("Factory not defined for object: ["
								+ this.objectRef.getTargetId()
								+ ":"
								+ this.objectRef.getTargetType()
						 		+ "]");
				 
				 Map<String, Object> effectiveProperties = createEffectiveProperties(targetConfig, instructions);
				 this.generatedResult = producerService.getProducerForType(factoryType).getFactoryById(factoryId)
						 .generate(EntaxyFactory.CONFIGURATION.OUTPUTS.OUTPUT_TYPE_REF
								 , EntaxyFactory.SCOPE.PRIVATE.label
								 , effectiveProperties);
				 
			} else {
				 JsonObject targetConfig = targetObject.origin.deepCopy();
				 JsonObject currentConfig = this.objectRef.origin;
				 JSONUtils.mergeObjects(currentConfig, targetConfig);
			
				 // System.out.println("\n\n\tGENERATING REF WITH CONFIG: \n\t" + targetConfig);
				 
				 String factoryId = targetConfig.has(FIELDS.FACTORY_ID)
						 ?targetConfig.get(FIELDS.FACTORY_ID).getAsString()
						 :"";

				 String factoryType = targetConfig.has(FIELDS.OBJECT_TYPE)
						 ?targetConfig.get(FIELDS.OBJECT_TYPE).getAsString()
						 :"";
				 
				 if (!CommonUtils.isValid(factoryId) || !CommonUtils.isValid(factoryType))
					 throw new IllegalArgumentException("Factory not defined for object: ["
								+ this.objectRef.getTargetId()
								+ ":"
								+ this.objectRef.getTargetType()
						 		+ "]");
				 
				 Map<String, Object> effectiveProperties = createEffectiveProperties(targetConfig, instructions);
				 this.generatedResult = producerService.getProducerForType(factoryType).getFactoryById(factoryId)
						 .generate(EntaxyFactory.CONFIGURATION.OUTPUTS.OUTPUT_TYPE_REF
								 , EntaxyFactory.SCOPE.PRIVATE.label
								 , effectiveProperties);
				
			}
		}
		return true;
	}
	protected Map<String, Object> createEffectiveProperties(JsonObject config, Map<String, Object> instructions){
		Map<String, Object> result = new HashMap<>();
		result.put(GenerateTask.INSTRUCTIONS_FIELD, instructions);
		JsonElement effectiveProperties = config.has(FIELDS.PROPERTIES) 
				?config.get(FIELDS.PROPERTIES)
				:new JsonObject();		
		if (effectiveProperties.isJsonObject()) {
			JsonObject jobj = effectiveProperties.getAsJsonObject();
			for (Entry<String, JsonElement> entry: config.deepCopy().entrySet()) {
				/*if (entry.getKey().equals(FIELDS.PROPERTIES))
					continue;*/
				if (jobj.has(entry.getKey()))
					continue;
				jobj.add(entry.getKey(), entry.getValue());
			}
			result.putAll(JSONUtils.element2map(effectiveProperties));	
		}
		return result;
	}

	@Override
	public boolean isFinal() {
		return false;
	}
}
