;;
;; zenirc-fancy-format.el - ben@piglet.cr.usgs.gov and mycroft@ai.mit.edu
;;
;; $Header: /home/fsf/friedman/src/zenirc/zenirc/scripts/RCS/zenirc-fancy-format.el,v 1.6 1993/10/19 02:30:13 rmtodd Exp $
;;
;; format nick!user@host info the first time you see someone as
;; nick!user@host and thereafter as just nick. Nick changes are detected
;; and handled correctly.
;;
;; you might want to preload zenirc-nickuserhost-list with people you usually
;; see on irc.
;;
;; Entries are moved to the front of the alist as they are used.  This should
;; save a lot of time in (assoc) as groups of messages tend to be from a small
;; group of people.
;; 
(defvar zenirc-nickuserhost-list '()
  "*Association list of ("nick" . "nick!user@host") pairs that you have already seen")

(defun zenirc-format-nickuserhost-hook (nickuserhost)
  (let ((nick (zenirc-extract-nick nickuserhost)))
    (if nick
	(let ((entry (assoc nick zenirc-nickuserhost-list)))
	  (if entry
	      (progn
		(if (not (eq (car zenirc-nickuserhost-list) entry))
		    (setq zenirc-nickuserhost-list
			  (cons entry (delq entry zenirc-nickuserhost-list))))
		(if (string= nickuserhost (cdr entry))
		    (zenirc-extract-nick nickuserhost)
		  (setcdr entry nickuserhost)))
	    (setq zenirc-nickuserhost-list (cons (cons nick nickuserhost) 
						 zenirc-nickuserhost-list))
	    nickuserhost))
      nickuserhost)))

(defun zenirc-server-NICK-hook (proc parsedmsg)
  (let* ((from (aref parsedmsg 1))
	 (entry (assoc (zenirc-extract-nick from) zenirc-nickuserhost-list)))
    (if entry
	(if (string= (aref parsedmsg 1) (cdr entry))
	    (zenirc-format-nickuserhost-hook
	     (concat (aref parsedmsg 2) (substring 
					from (string-match "[!@]" from)))))))
  (zenirc-server-NICK proc parsedmsg))
  
;;
;; Also hook into the /who display.  (added by rmtodd@servalan.servalan.com)
;;
(defun zenirc-server-352-hook (proc parsedmsg)
  (if (not (string= (aref parsedmsg 3) "Channel"))
      ;; It's not the header, snarf the nick, user, host out of it. 
      (let* ((nick (aref parsedmsg 7))
	     (nickuserhost (concat nick "!" (aref parsedmsg 4) "@" (aref parsedmsg 5)))
	     (entry (assoc nick zenirc-nickuserhost-list)))
	(if entry 
	    ;; is on the list, check if it matches the current userhost.
	    (if (not (string= nickuserhost (cdr entry)))
		;; Nope, so let zenirc-format-nickuserhost-hook add it.
		(zenirc-format-nickuserhost-hook nickuserhost)
	      )
	  ;; Not on the list, so add it using zenirc-format-nickuserhost-hook
	  (zenirc-format-nickuserhost-hook nickuserhost)
	  )
	)
    )
  (zenirc-server-352 proc parsedmsg))
