package com.example.bookstore.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.example.bookstore.OrderService;
import com.example.bookstore.model.Order;
import com.example.bookstore.model.OrderDetail;

public class OrderServiceImpl implements OrderService {

    static final Log log = LogFactory.getLog(OrderServiceImpl.class);

    Map<Long, Order> orderMap = new LinkedHashMap<Long, Order>();

    long lastOrderId = 1000;
    long lastOrderDetailId = 10000;

    public Order orderBook(Order order) {
        order.setId(nextOrderId());
        for (OrderDetail detail : order.getDetails()) {
            detail.setId(nextOrderDetailId());
        }
        orderMap.put(order.getId(), order);
        if (log.isInfoEnabled()) {
            log.info("Order book: " + order);
        }
        return order;
    }

    public Collection<Order> getOrdersForCustomer(long customerId) {
        List<Order> orders = new ArrayList<Order>();
        for (Order order : orderMap.values()) {
            if (order.getCustomer().getId() == customerId) {
                orders.add(order);
            }
        }
        return orders;
    }

    public Order getOrder(long orderId) {
        return orderMap.get(orderId);
    }

    long nextOrderId() {
        return ++lastOrderId;
    }

    long nextOrderDetailId() {
        return ++lastOrderDetailId;
    }

}
