(include "../ulex/ulex.scm")

(module ulex-test *
	
(import scheme
	(chicken io)
	(chicken base)
	(chicken time)
	(chicken file)
	(chicken file posix)
        (chicken string)
	(chicken process-context)
	(chicken process-context posix)
        miscmacros
;;         nng
        srfi-18
	srfi-69
        test
	matchable
	typed-records
	system-information
	directory-utils

	ulex
	)

(define help "Usage: ulex-test COMMAND
  where COMMAND is one of:
    run host:port  : start test server - start several in same dir
")

(define (call uconn msg addr)
  (print "Call for : " addr)
  (print "Sent: "msg" to " addr ", received: "
	 (send-receive uconn addr 'hello msg)))

;; start    => hello 0
;; hello 0  => hello 1
;; hello 1  => hello 2
;;  ...
;; hello 11 => 'done
;;
(define (process-message mesg)
  (print "In process-message")
  (let ((parts (string-split mesg)))
    (match
     parts
     ((msg c)
      (let ((count (string->number c)))
	(if (> count 10)
	    'done
	    (conc msg " " (if count count 0)))))
     ((msg)
      (conc msg " 0"))
     (else
      "hello 0"))))

(define (main)
(let* ((th1 (make-thread (lambda ()
  (match
   (command-line-arguments)
   ((run myport newport)
      (print "New stuff for IPC")
      (let* ((port (string->number myport))
              (endtimes (+ (current-seconds) 60))
              (handler (lambda (rem-host-port qrykey cmd params)
                   (process-message params)
                   ;;"hello1"
               ))
              (uconn (run-listener handler port)))
      (print "Listener up")
      ;;(thread-sleep! 8.0)
      (call uconn (conc "hello-from-"myport"-to-"newport) (conc newport))
      (let loop ((entries 0))  
        (call uconn (conc "hello-from-"myport"-to-"newport) (conc newport))
        (thread-sleep! 0.1)
      (loop 1))
      )
   )
   ((cmd)(print "ERROR: command "cmd", not recognised.\n\n"help))
   (else
    (print help))))
))
(th2 (make-thread (lambda()
  (let loop2 ((entries 1))
      (loop2 1)))))
)
(thread-start! th1)
(thread-start! th2)
(thread-join! th2)
))

) ;; end module

(import ulex-test)
(main)


