(use telemetry)

;; @startuml
;; Alice -> Bob: Authentication Request
;; Bob --> Alice: Authentication Response

;; Alice -> Bob: Another authentication Request
;; Alice <-- Bob: Another authentication Response
;;
;; ref over Bob
;;   This can be on
;;   several lines
;; end ref
;;
;; @enduml
(define *actor-table* (make-hash-table))
(define *actor-next-id* 0)
(define (get-actor-name key)
  (let* ((cast (string-split "Alice,Bob,Carol,Dave,Eve,Frank,Grace,Heidi,Ivan,Judy,Mallory,Nancy,Oscar,Peggy,Rupert,Sybil,Ted,Victor,Wendy" ","))
         (cast-count (length cast))
         (name (hash-table-ref/default *actor-table* key #f)))
    (cond
     (name name)
     (else
      (let* ((id *actor-next-id*)
             (name (list-ref cast (modulo id cast-count)))
             (seq (inexact->exact (floor (/ id cast-count))))
             (newname
              (conc
               name
               (if (> seq 0)
                   (conc "-" seq)
                   ""))))
        (set! *actor-next-id* (add1 *actor-next-id*))
        (hash-table-set! *actor-table* key newname)
        newname)))))
    

(define (ulex-telemetry-server)
  (let* ((port 12345)
         (seq 0)
         (handler (lambda (msg)
                    (set! seq (add1 seq))
                    (let* ((elapsed-ms (current-milliseconds))
                           (payload    (alist-ref 'payload msg))
                           (action     (if payload (alist-ref 'action   payload)))
                           (from-key   (if payload (alist-ref 'from-key payload)))
                           (to-key     (if payload (alist-ref 'to-key   payload)))
                           )
                      (if (and action from-key to-key)
                          (print (get-actor-name from-key) " -> " (get-actor-name to-key) ": "action))
                      ;;(pp msg)
                      ))))
    (telemetry-server port handler)))

(ulex-telemetry-server)
  
