#lang syndicate ;; -*- racket -*-

(require (only-in racket/string string-trim))
(require "../drivers/tcp.rkt")
(require "../demand-matcher.rkt")

(define (spawn-session them us)
  (define user (gensym 'user))
  (define (send-to-remote fmt . vs)
    (send! (at-meta (tcp-channel us them (string->bytes/utf-8 (apply format fmt vs))))))
  (define (say who fmt . vs)
    (unless (equal? who user) (send-to-remote "~a ~a\n" who (apply format fmt vs))))
  (actor (send-to-remote "Welcome, ~a.\n" user)
         (until (retracted (advertise (tcp-channel them us ?)) #:meta-level 1)
           (assert (advertise (tcp-channel us them ?) #:meta-level 1))
           (assert (advertise `(,user says ,?)))
           (on (asserted (advertise `(,$who says ,?))) (say who "arrived."))
           (on (retracted (advertise `(,$who says ,?))) (say who "departed."))
           (on `(,$who says ,$what) (say who "says: ~a" what))
           (on (message (at-meta (tcp-channel them us $bs)))
               (define input-string (string-trim (bytes->string/utf-8 bs)))
               (if (equal? input-string "quit-dataspace")
                   (assert! 'quit-dataspace)
                   (send! `(,user says ,input-string)))))
         (send-to-remote "Goodbye!\n")))

(spawn-tcp-driver)
(let ((us (tcp-listener 5999)))
  (group (until (asserted 'quit-dataspace)
           (on (asserted (advertise (tcp-channel $them us ?)) #:meta-level 1)
               (spawn-session them us)))))
