/*
 * Copyright 2002-2012 the original author or authors.
 *
 * 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.
 */
package org.springframework.integration.print.config.xml;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.integration.print.core.PrintServiceExecutor;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

/**
 * Contains various utility methods for parsing Print Adapter specific namesspace
 * elements and generating the respective {@link BeanDefinition}s.
 *
 * @author Gunnar Hillert
 *
 * @since 1.0
 *
 */
public final class PrintParserUtils {

	/** Prevent instantiation. */
	private PrintParserUtils() {
		throw new AssertionError();
	}

	/**
	 * Create a new {@link BeanDefinitionBuilder} for the class {@link PrintServiceExecutor}.

	 * @param element Must not be null
	 * @param parserContext Must not be null
	 * @return The BeanDefinitionBuilder for the {@link PrintServiceExecutor}
	 */
	public static BeanDefinitionBuilder getPrintServiceExecutorBuilder(final Element element,
															final ParserContext parserContext) {

		Assert.notNull(element,       "The provided element must not be null.");
		Assert.notNull(parserContext, "The provided parserContext must not be null.");

		final Object source = parserContext.extractSource(element);

		final BeanDefinitionBuilder printServiceExecutorBuilder = BeanDefinitionBuilder.genericBeanDefinition(PrintServiceExecutor.class);

		final String printServiceRef = element.getAttribute("print-service-ref");
		final String printerName = element.getAttribute("printer-name");

		if (StringUtils.hasText(printServiceRef)
				&& StringUtils.hasText(printerName)) {

			parserContext.getReaderContext().error("Exactly only one of the attributes 'print-service-ref' or " +
						"'printer-name' must be be set.", source);

		}

		if (StringUtils.hasText(printServiceRef)) {
			printServiceExecutorBuilder.addConstructorArgReference(printServiceRef);
		}

		if (StringUtils.hasText(printerName)) {
			printServiceExecutorBuilder.addConstructorArgReference(printerName);
		}

		return printServiceExecutorBuilder;

	}

}
