/***************************************************************************
 * Copyright 2014 Kieker Project (http://kieker-monitoring.net)
 *
 * 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 kieker.webgui.web.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import kieker.webgui.domain.Role;

/**
 * This converter can convert between instances of {@link String} and {@link Role}. This is necessary in the JSF context.
 * 
 * @author Nils Christian Ehmke
 */
@FacesConverter("roleStringConverter")
public final class RoleStringConverter implements Converter {

	/**
	 * Creates a new instance of this class. <b>Do not use this constructor. This converter is JSF managed.</b>
	 */
	public RoleStringConverter() {
		// No code necessary
	}

	@Override
	public Object getAsObject(final FacesContext context, final UIComponent comp, final String str) {
		if (str == null) {
			return null;
		} else {
			try {
				return Role.valueOf(str);
			} catch (final IllegalArgumentException ex) {
				throw new ConverterException("The given string does not represent a valid role", ex);
			}
		}
	}

	@Override
	public String getAsString(final FacesContext context, final UIComponent comp, final Object obj) {
		if (obj == null) {
			return "";
		} else if (obj instanceof Role) {
			return ((Role) obj).toString();
		} else {
			throw new ConverterException("The given object is not an instance of " + Role.class.getName());
		}
	}

}
