package various.converter;

import javax.faces.application.FacesMessage;
import javax.faces.component.StateHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import com.sun.faces.util.MessageFactory;
import various.ZipCode;

/**
 * Klasa konwertera kodów pocztowych (patrz rozdzial 5.3)
 *
 */
public class ZipCodeConverter implements Converter, StateHolder {

	public final static String CONVERTER_ID = "various.ZipCodeConverter";
	public static final String CONVERSION_ERROR_MESSAGE_ID = "various.ZipCodeConverter.ERROR";

	private String separator = null;

	public String getSeparator() {
		return separator;
	}

	public void setSeparator(String separator) {
		this.separator = separator;
	}


	public Object getAsObject(FacesContext context, UIComponent component,
			String value) throws ConverterException {
		if (value.isEmpty()) {
			return null;
		}

		ZipCode code = new ZipCode();
		if (separator == null)
			separator = "-";
		String[] array = value.split(separator);
		int arraySize = array.length;
		if (arraySize != 2) {
			FacesMessage errMsg = MessageFactory.getMessage(context,
					CONVERSION_ERROR_MESSAGE_ID, (new Object[] { value,
							separator }));
			if (errMsg == null)
				errMsg = new FacesMessage("Conversion Error");
			throw new ConverterException(errMsg);
		}
		code.setAreaCode(array[0]);
		code.setOfficeCode(array[1]);

		return code;
	}

	public String getAsString(FacesContext context, UIComponent component,
			Object value) {

		return ((ZipCode) value).getAreaCode() + separator
				+ ((ZipCode) value).getOfficeCode();
	}

	@Override
	public boolean isTransient() {
		return false;
	}

	@Override
	public void restoreState(FacesContext arg0, Object arg) {
		setSeparator((String) ((Object[]) arg)[0]);
	}

	@Override
	public Object saveState(FacesContext arg0) {
		Object[] values = new Object[1];
		values[0] = separator;
		return values;
	}

	@Override
	public void setTransient(boolean arg0) {

	}

}
