#lang imperative-syndicate

(require/activate imperative-syndicate/drivers/tcp)
(require racket/format)

(message-struct speak (who what))
(assertion-struct present (who))

(message-struct stop-server ())

(spawn #:name 'chat-server
       (stop-when (message (stop-server)))
       (during/spawn (tcp-connection $id (tcp-listener 5999))
         #:name (list 'chat-connection id)
         (assert (tcp-accepted id))
         (let ((me (gensym 'user)))
           (assert (present me))
           (on (message (tcp-in-line id $bs))
               (match bs
                 [#"/quit" (stop-current-facet)]
                 [#"/stop-server" (send! (stop-server))]
                 [_ (send! (speak me (bytes->string/utf-8 bs)))])))
         (during (present $user)
           (on-start (send! (tcp-out id (string->bytes/utf-8 (~a user " arrived\n")))))
           (on-stop  (send! (tcp-out id (string->bytes/utf-8 (~a user " left\n")))))
           (on (message (speak user $text))
               (send! (tcp-out id (string->bytes/utf-8 (~a user " says '" text "'\n"))))))))
