// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package nosql.mongodb.object;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Transient;

@Entity
public class Order {
    private int orderId;
    private String customer;
    private List<OrderLine> items;
    public Order() {
        this(0, "");
    }
    public Order(int orderId, String customer) {
        this(orderId, customer, new ArrayList<OrderLine>());
    }
    public Order(int orderId, String customer, List<OrderLine> items) {
        this.orderId = orderId;
        this.customer = customer;
        this.items = items;
    }
    @Id
    public int getOrderId() {
        return orderId;
    }
    public void setOrderId(int orderId) {
        this.orderId = orderId;
    }
    public String getCustomer() {
        return customer;
    }
    public void setCustomer(String customer) {
        this.customer = customer;
    }
    @OneToMany(mappedBy="order", cascade=CascadeType.ALL)
    public List<OrderLine> getItems() {
        return items;
    }
    public void setItems(List<OrderLine> items) {
        this.items = items;
    }
    @Transient
    public BigDecimal getPrice() {
        BigDecimal res = BigDecimal.ZERO;
        for(OrderLine ol : items) {
            res = res.add(ol.getPrice());
        }
        return res;
    }
    public void add(OrderLine ol) {
        getItems().add(ol);
        ol.setOrder(this);
    }
    @Override
    public String toString() {
        return String.format("(%d,%s,%s)", orderId, customer, items.stream().map(ol -> ol.toString()).collect(Collectors.joining(",")));
    }
}
