#lang imperative-syndicate

(require/activate imperative-syndicate/drivers/tcp)
(require/activate imperative-syndicate/drivers/external-event)
(require/activate imperative-syndicate/reassert)
(require (only-in racket/port read-bytes-line-evt))

(spawn (define id 'chat)
       (define root-facet (current-facet))

       (reassert-on (tcp-connection id (tcp-address "localhost" 5999))
                    (retracted (tcp-accepted id))
                    (asserted (tcp-rejected id _)))

       (on (asserted (tcp-rejected id $reason))
           (printf "*** ~a\n" (exn-message reason)))

       (during (tcp-accepted id)
         (on-start (printf "*** Connected.\n"))
         (on (retracted (tcp-accepted id)) (printf "*** Remote EOF.\n"))
         ;; ^ Not on-stop, because the facet is stopped by local EOF too!

         (on (message (tcp-in id $bs))
             (write-bytes bs)
             (flush-output))

         (define stdin-evt (read-bytes-line-evt (current-input-port) 'any))
         (on (message (inbound (external-event stdin-evt (list $line))))
             (if (eof-object? line)
                 (stop-facet root-facet (printf "*** Local EOF. Terminating.\n"))
                 (send! (tcp-out id (bytes-append line #"\n")))))))
