/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 *
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.exts.xwork2.converter.converters;

import java.net.URL;
import java.util.Map;

import nuts.core.lang.ArrayUtils;
import nuts.core.lang.StringUtils;

/**
 */
public class URLTypeConverter extends AbstractTypeConverter {

	/**
	 * Converts one or more String values to the specified class.
	 * 
	 * @param context the action context
	 * @param values the String values to be converted, such as those submitted from an HTML form
	 * @param toClass the class to convert to
	 * @return the converted object
	 */
	public Object convertFromString(Map context, String[] values, Class toClass) {
		if (ArrayUtils.isEmpty(values) || StringUtils.isEmpty(values[0])) {
			return null;
		}

		try {
			return new URL(values[0]);
		}
		catch (Exception e) {
			throw new IllegalArgumentException("Can't convert [" + values[0] + "] to URL.");
		}
	}

	/**
	 * Converts the specified object to a String.
	 * 
	 * @param context the action context
	 * @param o the object to be converted
	 * @return the converted String
	 */
	public String convertToString(Map context, Object o) {
		return o == null ? null : o.toString();
	}
}
