 M: join handle-incoming-irc ( join -- )
     irc-client> join-messages>> mailbox-put ;
 
-M: irc-end handle-incoming-irc ( irc-end -- )
-    irc-client> listeners>> values [ in-messages>> mailbox-put ] with each ;
+M: irc-broadcasted-message handle-incoming-irc ( irc-broadcasted-message -- )
+    broadcast-message-to-listeners ;
 
 ! ======================================
 ! Client message handling

! Listener join request handling
! ======================================

: make-registered-listener ( name -- listener )
    <irc-listener>
    [ [ listener-loop ] 2curry "listener" spawn-irc-loop ]
    [ swap [ irc-client> listeners>> set-at ] curry keep ]
    2bi ;

: make-join-future ( name -- future )
    [ [ swap trailing>> = ] curry ! compare name with channel name
      irc-client> join-messages>> 60 seconds rot mailbox-get-timeout?
      trailing>> make-registered-listener ]
    curry future ;

: make-user-future ( name -- future )
    [ make-registered-listener ] curry future ;

: maybe-join ( name password -- ? )
    over "#" head? [ /JOIN t ] [ 2drop f ] if ;

: make-listener-future ( name channel? -- future )
    [ make-join-future ] [ make-user-future ] if ;

PRIVATE>


: irc-message-origin ( irc-message -- name )
    dup name>> me? [ prefix>> parse-name ] [ name>> ] if ;

: broadcast-message-to-listeners ( message -- )
    irc-client> listeners>> values [ in-messages>> mailbox-put ] with each ;

GENERIC: handle-incoming-irc ( irc-message -- )

M: irc-message handle-incoming-irc ( irc-message -- )
