/*-
 * ~~~~~~licensing~~~~~~
 * object-producer-core
 * ==========
 * 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.merge;

import java.util.Map;

import org.osgi.service.component.annotations.Component;
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.platform.runtime.base.connecting.generator.Generated;
import ru.entaxy.platform.base.support.xml.CommonXMLUtils;
import ru.entaxy.platform.core.producer.executor.generationmodel.merge.MergingMap.Mapping;

@Component(service = MergeProcessor.class, immediate = true)
@MergingMap(mappings = {
	@Mapping(source = Generated.GENERATED_TYPE_BLUEPRINT_FRAGMENT, targets = {Generated.GENERATED_TYPE_BLUEPRINT})	
})
public class BlueprintMergeProcessor extends AbstractMergeProcessor {

	private static final Logger log = LoggerFactory.getLogger(BlueprintMergeProcessor.class);
	
	@Override
	public Generated merge(Generated source, Generated target, Map<String, Object> config) {
		
		NodeList sourceNodes = null;
		if (source.getType().equals(Generated.GENERATED_TYPE_BLUEPRINT_FRAGMENT)) {
			String toParse = "<fragment>" + source.getObject().toString() + "</fragment>";
			try {
				Document sourceDoc = CommonXMLUtils.parseString(true, toParse);
				sourceNodes = sourceDoc.getFirstChild().getChildNodes();
				for (int i=0; i<sourceNodes.getLength(); i++) {
					Node node = sourceNodes.item(i);
				}
			} catch (Exception e) {
				log.error("Can't parse: \n" + toParse, e);
			}
		}
		
		if ((sourceNodes == null) || (sourceNodes.getLength()==0))
			return target;
		
		Document targetDoc = null;
		Node targetNode = null;
		Node targetNodeBefore = null;
		if (target.getType().equals(Generated.GENERATED_TYPE_BLUEPRINT)) {
			try {
				targetDoc = CommonXMLUtils.parseString(true, target.getObject().toString());
				targetNode = targetDoc.getFirstChild();
				
				NodeList manifests = targetDoc.getElementsByTagName("manifest");
				for (int i=0; i<manifests.getLength(); i++)
					if ((manifests.item(i).getParentNode() != null) && (manifests.item(i).getParentNode() == targetNode)) {
						targetNodeBefore = manifests.item(i).getNextSibling();
						break;
					}
				
				
			} catch (Exception e) {
				log.error("Can't parse: \n" + target.getObject().toString(), e);
			}
		}
		
		if (targetNode == null)
			return null;
		
		if (targetNode.getChildNodes().getLength()==0)
			for (int i=0; i<sourceNodes.getLength(); i++)
				targetNode.appendChild(targetDoc.adoptNode(sourceNodes.item(i).cloneNode(true)));
		else {
			if (targetNodeBefore == null)
				targetNodeBefore = targetNode.getFirstChild();
			for (int i=0; i<sourceNodes.getLength(); i++)
				targetNode.insertBefore(targetDoc.adoptNode(sourceNodes.item(i).cloneNode(true)), targetNodeBefore);
			
		}
		
		try {
			String resultBlueprint = CommonXMLUtils.doc2string(targetDoc);
			Generated result = Generated.create(Generated.GENERATED_TYPE_BLUEPRINT, resultBlueprint);
			result.getProperties().putAll(target.getProperties());
			return result;
		} catch (Exception e) {
			log.error("Can't convert to string", e);
		}
		
		
		return null;
	}

}
