#lang mzscheme
(require mzlib/etc
scheme/class
scheme/contract
scheme/match
srfi/19/time
(planet untyped/unlib:3/list)
"../snooze-mzscheme.ss"
"attribute.ss"
"cache.ss"
"delta.ss"
"entity.ss")
(define audit-frame%
(class delta-api%
(inherit id->entity
entity->id
id->attribute
attribute->id
make-insert-delta
make-update-delta
make-delete-delta)
(inherit-field snooze)
(init-field entity:audit-transaction)
(field [transaction #f])
(field [changes-made? #f])
(super-new)
(define/public (get-transaction)
transaction)
(define/public (init! . log-values)
(define attributes (entity-attributes entity:audit-transaction))
(define make-transaction (entity-constructor entity:audit-transaction))
(define args (list-pad-right (list* #f #f (current-time time-utc) log-values) (length attributes)))
(set! transaction (send snooze save! (apply make-transaction args))))
(define/public (clean-up!)
(unless changes-made?
(send snooze delete! transaction)))
(define/public (audit-insert! struct)
(define delta (make-insert-delta transaction (struct-guid struct)))
(send snooze save! delta)
(set! changes-made? #t))
(define/public (audit-update! new)
(define id (struct-id new))
(define entity (struct-entity new))
(define old (send snooze find-by-id entity id))
(define revision (struct-revision old))
(for-each (lambda (attr old-value new-value)
(unless (equal? old-value new-value)
(let* ( [attr-id (attribute->id attr)]
[attr-type (attribute-type attr)]
[delta (make-update-delta transaction (struct-guid new) revision attr old-value)])
(send snooze save! delta)
(set! changes-made? #t))))
(cddr (entity-attributes entity))
(cddr (struct-attributes old))
(cddr (struct-attributes new))))
(define/public (audit-delete! struct)
(define id (struct-id struct))
(define revision (struct-revision struct))
(define entity (struct-entity struct))
(for-each (lambda (attr value)
(define attr-id (attribute->id attr))
(define attr-type (attribute-type attr))
(define delta (make-delete-delta transaction (struct-guid struct) revision attr value))
(send snooze save! delta)
(set! changes-made? #t))
(cddr (entity-attributes entity))
(cddr (struct-attributes struct))))
(inspect #f)))
(provide audit-frame%)