/*-
 * ~~~~~~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.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.google.gson.Gson;

import ru.entaxy.platform.base.objects.EntaxyObject.FIELDS;
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.FactoredObjectRef;

public class ResolveRefTask extends AbstractRefTask {

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

	@Override
	public String getInfo() {
		return "RESOLVE-REF " 
				+ "[" 
				+ objectRef.definedIn.getObjectId() 
				+ "] -> " 
				+ "[" 
				+ objectRef.getTargetId() 
				+ "]"; 
				// + objectRef.factoryId;
	}

	@Override
	public boolean execute(ProducerResult currentResult, CommandResult currentCommand,
			EntaxyProducerService producerService, Map<String, Object> instructions) throws Exception {
		GenerationModel generationModel = currentResult.findResultObject(GenerationModel.class);
		String fieldName = objectRef.getOrDefault(FIELDS.REF_FIELD, FIELDS.OBJECT_ID).toString();
		printOutput("RESOLVING REF TO FIELD [" + fieldName + "]");
		List<AbstractTask> generateTasks = generationModel.tasks.stream()
				.filter(t->(t instanceof GenerateTask))
				.map(t->(GenerateTask)t)
				.filter(t->t.origin==objectRef.getTargetObject())
				.collect(Collectors.toList());
		if (generateTasks.size() == 0)
			generateTasks = generationModel.tasks.stream()
					.filter(t->(t instanceof ResolveObjectTask))
					.map(t->(ResolveObjectTask)t)
					.filter(t->t.origin==objectRef.getTargetObject())
					.collect(Collectors.toList());
		if (generateTasks.size() == 0) {
			printOutput("None of GenerateTask or ResolveObjectTask found for [" + objectRef.getTargetId() + "/" + objectRef.getTargetObject().getObjectType() + "]");
			return false;
		}
		AbstractTask provider = generateTasks.get(0);
		Object value = null;
		if (provider instanceof GenerateTask) {
			GenerateTask generateTask = (GenerateTask)provider;
			value = generateTask.generationProperties.getOrDefault(fieldName, "");
		} else if (provider instanceof ResolveObjectTask) {
			ResolveObjectTask task = (ResolveObjectTask)provider;
			value = ObjectResolveHelper.getInstance().resolve(task.targetObject, fieldName);
			if (value == null)
				value = "";
		}
		printOutput("RESOLVED REF TO FIELD [" + fieldName + "] to VALUE [" + value.toString() + "]");
		printOutput("REPLACE: [" + objectRef.origin.toString() + "] in PATH [" 
				+ objectRef.relativePath + "] in OBJECT " 
				+ objectRef.definedIn.origin.toString() );
		JSONUtils.replaceValue(objectRef.definedIn.origin, objectRef.relativePath, (new Gson()).toJsonTree(value));
		printOutput("AFTER REPLACEMENT: [" + objectRef.definedIn.origin.toString() + "]");
		return true;
	}

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