class PurchaseOrderService {

    boolean transactional = false

    PurchaseOrderNumber findNextUnusedPurchaseOrderNumber() {
        def empty = PurchaseOrderNumber.list().find{it.purchaseOrder==null}
        return empty
    }

    PurchaseOrder getOrCreatePurchaseOrder(params) {
        def id = params.purchaseOrderNumber.id
        if (params.purchaseOrderNumber.id instanceof Long) {
            id = params.purchaseOrderNumber.id
        } else {
            id = params.purchaseOrderNumber.id.toString().toLong()
        }
        def pon = PurchaseOrderNumber.get(id)
        def po = pon?.purchaseOrder
        if (!po) {
            po = createPurchaseOrder(pon,params)
        }
        return po
    }

    PurchaseOrder createPurchaseOrder(pon,params) {
        def supplier = Supplier.get(params.supplier.id)
        def po = new PurchaseOrder(supplier:supplier)
        pon.purchaseOrder = po
        po.purchaseOrderNumber = pon
        pon.save(failOnError:true) // should cascade to save the PO as well. I wonder why it doesn't.
        po.save(failOnError:true)
        return po
    }

    List<PurchaseOrder> findDraftPurchaseOrderNumbers() {
        def drafts = PurchaseOrder.list().findAll{it.ordered == null}.collect{it.purchaseOrderNumber}
        return drafts
    }
}
