import React from 'react';
import {create as createXML}  from 'xmlbuilder2';
import { XMLBuilder, XMLBuilderCreateOptions, DefaultBuilderOptions, XMLWriterOptions } from "xmlbuilder2/lib/interfaces";

function renderXMLElement(root: XMLBuilder, {type, props}: React.ReactElement) {
	let node = root;

	if (typeof type !== 'symbol') {
		const elementName = typeof type == 'function' ? type.name: type;
		
		if (typeof type == 'function') {
			let e: React.ReactElement;
			
			if (!!(type.prototype && type.prototype.isReactComponent)) {
				e = new (type as any)(props).render();
			} else {
				e = (type as Function)(props);
			}
			
			return renderXMLElement(root, e);
		}
		
		node = root.ele(elementName, (({children, ...props}: {children?: any, [props: string]: any}) => props)(props));
	}
	
	if ('children' in props) {	
		React.Children.map(props.children, child => {
			if (React.isValidElement(child)) {
				renderXMLElement(node, child);
			} else {
				node.txt(String(child));
			}
		})
	}
	
	if (root != node)
		node.up();
	
	return root;
}

export default {
	renderToString(element: React.ReactElement, writerOptions: XMLWriterOptions = {}, builderOptions: XMLBuilderCreateOptions = DefaultBuilderOptions):string {
		return renderXMLElement(createXML(builderOptions), element).end(writerOptions);
	}
}
