/*-
 * ~~~~~~licensing~~~~~~
 * object-producing-resources-support
 * ==========
 * 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.resources.processors;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.base.support.xml.CommonXMLUtils;
import ru.entaxy.platform.core.producer.resources.EntaxyResourceProducingProcessor;

@Component (service = EntaxyResourceProducingProcessor.class, immediate = true)
public class MergeResourceProcessor implements EntaxyResourceProducingProcessor {

	private static final Logger log = LoggerFactory.getLogger(MergeResourceProcessor.class);

	public static final String PROP_SOURCE = "source";
	public static final String PROP_SOURCE_ELEMENT = "sourceElement";
	public static final String PROP_TARGET_ELEMENT = "targetElement";
	
	@Reference(cardinality = ReferenceCardinality.MANDATORY)
	EntaxyResourceService entaxyResourceService;
	
	@Override
	public String getName() {
		return "merge";
	}

	@Override
	public Object process(Object value, Map<String, Object> properties) throws Exception{
		if (value == null)
			return value;
		
		Object valueToReturn = null;
		
		String sourceLocation = properties.getOrDefault(PROP_SOURCE, "").toString();
		if (!CommonUtils.isValid(sourceLocation)) {
			log.warn("'source' not defined in [{}]", properties);
			//			TODO throw exception?
			return value;
		}
		
		EntaxyResource resource = entaxyResourceService.getResource(sourceLocation);
		if (!resource.exists()) {
			log.warn("Source [{}] not found, was defined in [{}]", sourceLocation, properties);
			//			TODO throw exception?
			return value;
		}
		
		String sourceElement = properties.getOrDefault(PROP_SOURCE_ELEMENT, "").toString();
		if (!CommonUtils.isValid(sourceElement)) {
			log.warn("Source element not defined in [{}]", properties);
			//			TODO throw exception?
			return value;
		}

		String targetElement = properties.getOrDefault(PROP_TARGET_ELEMENT, "").toString();
		if (!CommonUtils.isValid(targetElement)) {
			log.warn("Target element not defined in [{}]", properties);
			//			TODO throw exception?
			return value;
		}
		
		String targetXMLString = value.toString();
		String sourceXMLString = resource.getAsString();
		
		try {
			Document targetDocument = CommonXMLUtils.parseString(false, targetXMLString);
			Document sourceDocument = CommonXMLUtils.parseString(false, sourceXMLString);
			
			NodeList nodesToReplace = targetDocument.getElementsByTagName(targetElement);
			if (nodesToReplace.getLength() == 0)
				return value;
			
			NodeList replacements = sourceDocument.getElementsByTagName(sourceElement);
			if (replacements.getLength() == 0)
				return value;
			
			Node replacement = replacements.item(0);
			NodeList replacementChildren = replacement.getChildNodes();
			
			List<Node> toRemove = new ArrayList<>();
			
			for (int i=0; i<nodesToReplace.getLength(); i++) {
				Node toReplace = nodesToReplace.item(i);
				for (int j=0; j<replacementChildren.getLength(); j++) {
					Node adopted = targetDocument.adoptNode(replacementChildren.item(j).cloneNode(true));
					toReplace.getParentNode().insertBefore(adopted, toReplace);
				}
				toRemove.add(toReplace);
			}
			
			for (Node n: toRemove)
				n.getParentNode().removeChild(n);
			
			valueToReturn = CommonXMLUtils.doc2string(targetDocument);
			
		} catch (Exception e) {
			log.error("Error merging documents", e);
			throw e;
		}
		
		return valueToReturn;
	}

}
