package de.gefa.rewrite;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

import org.ocpsoft.rewrite.annotation.Join;
import org.ocpsoft.rewrite.annotation.Parameter;
import org.ocpsoft.rewrite.annotation.RequestAction;
import org.ocpsoft.rewrite.el.ELBeanName;
import org.ocpsoft.rewrite.faces.annotation.Deferred;
import org.ocpsoft.rewrite.faces.navigate.Navigate;

@Named
@SessionScoped
@ELBeanName("customerBean")
@Join(path = "/customer", to = "/jsf/customer.xhtml")
public class CustomerBean implements Serializable {

	private static final long serialVersionUID = -1522682558529300364L;

	// in reality, we would have an EJB here
	private final CustomerService customerService = new CustomerService();

	@Parameter
	@Deferred
	private String customerId;

	private Customer customer;

	public Navigate openCustomer()
	{
		refreshCustomer();

		return Navigate.to(CustomerBean.class).with("customerId", customerId);
	}

	@RequestAction
	@Deferred
	public void init()
	{
		refreshCustomer();
	}

	public String getCustomerId() {
		return customerId;
	}

	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}

	private void refreshCustomer() {
		if (customerId != null) {
			if (customer == null || (customer != null && !customerId.equals("" + customer.getId()))) {
				customer = customerService.loadCustomer();
			}
		}

	}

}
