/***************************************************************************
 * 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.beans.request.project;

import java.util.regex.Pattern;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import kieker.webgui.web.beans.application.GlobalPropertiesBean;

import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Nils Christian Ehmke
 */
public abstract class AbstractProjectBean {

	private static final Pattern PROJECT_NAME_PATTERN = Pattern.compile("\\w.*");

	private String projectName;
	private UIComponent messageTarget;

	@Autowired
	private GlobalPropertiesBean globalPropertiesBean;

	/**
	 * Default constructor.
	 */
	public AbstractProjectBean() {
		// No code necessary
	}

	/**
	 * This method initializes the object. <b>Do not call this method manually. It will only be accessed by Spring.</b>
	 */
	@PostConstruct
	public void initialize() {
		// We initialize the fields with localized default values
		this.projectName = this.globalPropertiesBean.getDefaultProjectName();
	}

	public String getProjectName() {
		return this.projectName;
	}

	public void setProjectName(final String projectName) {
		this.projectName = projectName;
	}

	public UIComponent getMessageTarget() {
		return this.messageTarget;
	}

	public void setMessageTarget(final UIComponent messageTarget) {
		this.messageTarget = messageTarget;
	}

	/**
	 * This method makes sure that the given project name is a valid one.
	 * 
	 * @param context
	 *            The faces context.
	 * @param toValidate
	 *            The component.
	 * @param value
	 *            The value to validate (the project name).
	 */
	public void validateProjectName(final FacesContext context, final UIComponent toValidate, final Object value) {
		final String name = (String) value;

		if (!PROJECT_NAME_PATTERN.matcher(name).matches()) {
			throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, null, this.globalPropertiesBean.getMsgEnterValidName()));
		}
	}

}
