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