;;; liece-channel.el --- Various facility for channel operation.
;; Copyright (C) 1998-2000 Daiki Ueno

;; Author: Daiki Ueno <ueno@unixuser.org>
;; Created: 1998-09-28
;; Revised: 1999-05-05
;; Keywords: IRC, liece

;; This file is part of Liece.

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.


;;; Commentary:
;; 

;;; Code:

(eval-when-compile (require 'liece-inlines))

(eval-when-compile (require 'liece-clfns))

(defconst liece-channel-regexp "[+&#!]")
(defconst liece-channel-modeless-regexp "[+!]")

(defvar liece-default-channel-representation-format "%s+%s")

(defconst liece-dcc-channel-representation-format "=%s")

(define-widget 'liece-channel-push-button 'push-button
  "A channel button."
  :action 'liece-channel-push-button-action)

(defun liece-channel-push-button-action (widget &optional event)
  (let ((chnl (liece-channel-virtual (widget-value widget))))
    (if (or (liece-channel-member chnl liece-current-channels)
	    (y-or-n-p (format "Do you really join %s? " chnl)))
	(liece-command-join chnl))))

;;; Reader conventions
(defun liece-channel-p (chnl)
  (string-match (concat "^" liece-channel-regexp) chnl))

(defun liece-channel-modeless-p (chnl)
  (string-match (concat "^" liece-channel-modeless-regexp) chnl))

(defalias 'liece-channel-equal 'string-equal-ignore-case)

(defun liece-channel-member (chnl chnls)
  "Return non-nil if CHNL is member of CHNLS."
  (member-if
   (lambda (item)
     (and (stringp item) (liece-channel-equal chnl item)))
   chnls))

(defun liece-channel-unread-p (chnl)
  "Return non-nil if CHNL is unread channel."
  (member-if
   (lambda (item)
     (and (stringp item) (liece-channel-equal chnl item)))
   liece-channel-unread-list))

(defun liece-channel-get-nicks (&optional chnl)
  "Return CHNL or current channels's members as list."
  (get (intern (or chnl liece-current-channel) liece-obarray) 'nick))

(defun liece-channel-get-operators (&optional chnl)
  "Return CHNL or current channels's operators as list."
  (get (intern (or chnl liece-current-channel) liece-obarray) 'oper))

(defun liece-channel-get-voices (&optional chnl)
  "Return CHNL or current channels's voices as list."
  (get (intern (or chnl liece-current-channel) liece-obarray) 'voice))

(defun liece-channel-get-topic (&optional chnl)
  "Return CHNL or current channels's topic."
  (get (intern (or chnl liece-current-channel) liece-obarray) 'topic))

(defun liece-channel-get-modes (&optional chnl)
  "Return CHNL or current channels's mode."
  (get (intern (or chnl liece-current-channel) liece-obarray) 'mode))

(defun liece-channel-get-bans (&optional chnl)
  "Return CHNL or current channels's ban list."
  (get (intern (or chnl liece-current-channel) liece-obarray) 'ban))

(defun liece-channel-get-invites (&optional chnl)
  "Return CHNL or current channels's invite list."
  (get (intern (or chnl liece-current-channel) liece-obarray) 'invite))

(defun liece-channel-get-exceptions (&optional chnl)
  "Return CHNL or current channels's exception list."
  (get (intern (or chnl liece-current-channel) liece-obarray) 'exception))

;;; Channel status functions
(defun liece-channel-remove (channel channels)
  "Remove CHANNEL from CHANNELS."
  (remove-if
   (lambda (item)
     (and (stringp item) (liece-channel-equal channel item)))
   channels))

(defun liece-channel-delete (channel channels)
  "Delete CHANNEL from CHANNELS."
  (delete-if
   (lambda (item)
     (and (stringp item) (liece-channel-equal channel item)))
   channels))

(defun liece-channel-set-topic (topic &optional channel)
  "Set CHANNEL's topic."
  (put (intern (or channel liece-current-channel) liece-obarray)
       'topic topic))

(defun liece-channel-add-mode (mode &optional channel)
  "Add MODE to CHANNEL.
MODE is a string splitted into characters one by one."
  (let ((modes
	 (liece-string-to-list
	  (or (liece-channel-get-modes channel)
	      ""))))
    (or (memq mode modes)
	(push mode modes))
    (put (intern (or channel liece-current-channel) liece-obarray)
	 'mode (mapconcat #'char-to-string modes ""))))

(defun liece-channel-remove-mode (mode &optional channel)
  "Remove MODE from CHANNEL.
MODE is a string splitted into characters one by one."
  (let ((modes
	 (liece-string-to-list
	  (or (liece-channel-get-modes channel)
	      ""))))
    (delq mode modes)
    (put (intern (or channel liece-current-channel) liece-obarray)
	 'mode (mapconcat #'char-to-string modes ""))))

(defun liece-channel-set-mode (channel mode flag)
  "Add or remove channel MODE of CHANNEL.
MODE is a string splitted into characters one by one.
If FLAG is non-nil, given modes are added to the channel.
Otherwise they are removed from the channel."
  (if flag
      (liece-channel-add-mode mode channel)
    (liece-channel-remove-mode mode channel)))

(defun liece-channel-add-ban (pattern &optional channel)
  "Add ban PATTERN to CHANNEL."
  (let ((patterns (liece-channel-get-bans channel)))
    (or (string-list-member-ignore-case pattern patterns)
	(push pattern patterns))
    (put (intern (or channel liece-current-channel) liece-obarray)
	 'ban patterns)))

(defun liece-channel-remove-ban (pattern &optional channel)
  "Remove ban PATTERN from CHANNEL."
  (let ((patterns
	 (remove-if
	  (lambda (elm) (string-equal pattern elm))
	  (liece-channel-get-bans channel))))
    (put (intern (or channel liece-current-channel) liece-obarray)
	 'ban patterns)))

(defun liece-channel-set-ban (channel pattern flag)
  "Add or remove ban PATTERN to CHANNEL.
If FLAG is non-nil, given ban patterns are added to the channel.
Otherwise they are removed from the channel."
  (if flag
      (liece-channel-add-ban pattern channel)
    (liece-channel-remove-ban pattern channel)))

(defun liece-channel-add-exception (pattern &optional channel)
  "Add exception PATTERN to CHANNEL."
  (let ((patterns (liece-channel-get-exceptions channel)))
    (or (string-list-member-ignore-case pattern patterns)
	(push pattern patterns))
    (put (intern (or channel liece-current-channel) liece-obarray)
	 'exception patterns)))

(defun liece-channel-remove-exception (pattern &optional channel)
  "Remove exception PATTERN from CHANNEL."
  (let ((patterns
	 (remove-if
	  (lambda (elm) (string-equal pattern elm))
	  (liece-channel-get-exceptions channel))))
    (put (intern (or channel liece-current-channel) liece-obarray)
	 'exception patterns)))

(defun liece-channel-set-exception (channel pattern flag)
  "Add or remove exception PATTERN to CHANNEL.
If FLAG is non-nil, given exception patterns are added to the channel.
Otherwise they are removed from the channel."
  (if flag
      (liece-channel-add-exception pattern channel)
     (liece-channel-remove-exception pattern channel)))

(defun liece-channel-add-invite (pattern &optional channel)
  "Add invite PATTERN to CHANNEL."
  (let ((patterns (liece-channel-get-invites channel)))
    (or (string-list-member-ignore-case pattern patterns)
	(push pattern patterns))
    (put (intern (or channel liece-current-channel) liece-obarray)
	 'invite patterns)))

(defun liece-channel-remove-invite (pattern &optional channel)
  "Remove invite PATTERN from CHANNEL."
  (let ((patterns
	 (remove-if
	  (lambda (elm) (string-equal pattern elm))
	  (liece-channel-get-invites channel))))
    (put (intern (or channel liece-current-channel) liece-obarray)
	 'invite patterns)))

(defun liece-channel-set-invite (channel pattern flag)
  "Add or remove invite PATTERN to CHANNEL.
If FLAG is non-nil, given invite patterns are added to the channel.
Otherwise they are removed from the channel."
  (if flag
      (liece-channel-add-invite pattern channel)
     (liece-channel-remove-invite pattern channel)))
  
(defun liece-channel-virtual (channel)
  "Convert channel name into internal representation.
\(For example if CHANNEL is a string \"#...:*\", it will be converted into
\"%...\"\)"
  (let ((mapping liece-channel-conversion-map) match)
    (while mapping
      (if (string-equal-ignore-case (caar mapping) channel)
	  (setq match (cdar mapping)))
      (pop mapping))
    (if match
	match
      (save-match-data
	(cond
	 ((string-match
	   (format "^[#+]\\(.*\\):%s$"
		   (regexp-quote liece-channel-conversion-default-mask))
	   channel)
	  (if (eq ?+ (aref channel 0))
	      (concat "-" (match-string 1 channel))
	    (concat "%" (match-string 1 channel))))
;;;	 ((and (not (equal channel "")) (eq ?! (aref channel 0)))
;;;	  (concat "!" (substring channel (1+ liece-channel-id-length))))
	 (t channel))))))

(defun liece-channel-real (channel)
  "Convert channel name into external representation.
\(For example if CHANNEL is a string \"%...\", it will be converted into
\"#...:*\"\)"
  (let ((mapping liece-channel-conversion-map) match)
    (while mapping
      (if (string-equal-ignore-case (cdar mapping) channel)
	  (setq match (caar mapping)))
      (pop mapping))
    (cond
     (match match)
     ((eq ?% (aref channel 0))
      (concat "#" (substring channel 1) ":"
	      liece-channel-conversion-default-mask))
     ((eq ?- (aref channel 0))
      (concat "+" (substring channel 1) ":"
	      liece-channel-conversion-default-mask))
     (t channel))))

;;;###liece-autoload
(defun liece-command-toggle-channel-buffer-mode ()
  "Toggle visibility of channel buffer."
  (interactive)
  (if (get-buffer liece-channel-buffer)
      (setq liece-channel-buffer-mode (not liece-channel-buffer-mode)))
  (liece-configure-windows))

(defmacro liece-channel-buffer-create (chnl)
  "Create channel buffer of CHNL."
  `(with-current-buffer
       (liece-get-buffer-create (format liece-channel-buffer-format ,chnl))
     (let (buffer-read-only)
       (liece-insert-info (current-buffer)
			   (concat (funcall liece-format-time-function
					    (current-time))
				   " Created.\n")))
     (unless (eq major-mode 'liece-channel-mode)
       (liece-channel-mode))
     (set-alist 'liece-channel-buffer-alist ,chnl (current-buffer))
     (current-buffer)))

(defun liece-channel-join-internal (item chnls &optional hints)
  (let (binding inserted)
    (if (liece-channel-member item hints)
	(do ((hint hints (cdr hint)) (chnl chnls (cdr chnl)))
	    ((not (or hint chnl)))
	  (if (and (car hint) (liece-channel-equal (car hint) item))
	      (push item binding)
	    (push (car chnl) binding)))
      (do ((hint hints (cdr hint)) (chnl chnls (cdr chnl)))
	  ((not (or hint chnl)))
	(if (and (not inserted)
		 (not (or (car hint) (car chnl))))
	    (progn
	      (push item binding)
	      (setq inserted t))
	  (push (car chnl) binding))))
    (or (liece-channel-member item binding)
	(push item binding))
    (nreverse binding)))

(defun liece-channel-join (chnl &optional nosw)
  "Initialize channel variables of CHNL.
If NOSW is non-nil do not switch to newly created channel."
  (let ((cbuf (cdr (string-assoc-ignore-case chnl liece-channel-buffer-alist)))
	(nbuf (cdr (string-assoc-ignore-case chnl liece-nick-buffer-alist))))
    (or cbuf
	(setq cbuf (liece-channel-buffer-create chnl)))
    (or nbuf
	(setq nbuf (liece-nick-buffer-create chnl)))
    (if (liece-channel-p (liece-channel-real chnl))
	(setq liece-current-channels
	      (liece-channel-join-internal
	       chnl liece-current-channels liece-default-channel-binding))
      (setq liece-current-chat-partners
	    (liece-channel-join-internal chnl liece-current-chat-partners
					  liece-default-partner-binding)))
    (unless nosw
      (liece-switch-to-channel chnl)
      (setq liece-channel-buffer cbuf
	    liece-nick-buffer nbuf))
    (liece-channel-change)))

(defun liece-channel-part-internal (item chnls &optional hints)
  (if hints
      (mapcar
       (lambda (chnl)
	 (if (and chnl (liece-channel-equal item chnl)) nil chnl))
       chnls)
    (liece-channel-remove item chnls)))

(defun liece-channel-part (chnl &optional nosw)
  "Finalize channel variables of CHNL.
If NOSW is non-nil do not switch to newly created channel."
  (cond
   ((eq liece-command-buffer-mode 'chat)
    (setq liece-current-chat-partners
	  (liece-channel-part-internal chnl liece-current-chat-partners
					liece-default-partner-binding))
    (unless nosw
      (liece-channel-switch-to-last liece-current-chat-partners)))
   (t
    (setq liece-current-channels
	  (liece-channel-part-internal chnl liece-current-channels
				       liece-default-channel-binding))
    (unless nosw
      (liece-channel-switch-to-last liece-current-channels)))))

(defun liece-channel-last (chnls)
  (car (last (delq nil (copy-sequence chnls)))))

(defmacro liece-channel-switch-to-last (chnls)
  `(let ((chnl (liece-channel-last ,chnls)))
     (if chnl
	 (liece-switch-to-channel chnl))
     (liece-channel-change)))

(defun liece-channel-change ()
  (let ((chnls (if (eq liece-command-buffer-mode 'chat)
		   liece-current-chat-partners
		 liece-current-channels))
	(string "")
	chnl)
    (with-current-buffer liece-channel-list-buffer
      (let ((n 1) buffer-read-only)
	(erase-buffer)
	(dolist (chnl chnls)
	  (when chnl
	    (setq chnl (liece-channel-virtual chnl)
		  string (format "%s,%d:%s" string n chnl))
	    (liece-channel-list-add-button n chnl))
	  (incf n))))
    (if (string-equal string "")
	(if (eq liece-command-buffer-mode 'chat)
	    (setq liece-channels-indicator "No partner")
	  (setq liece-channels-indicator "No channel"))
      (setq liece-channels-indicator (substring string 1)))
    (liece-set-channel-indicator)
    (setq chnl (if (eq liece-command-buffer-mode 'chat)
		   liece-current-chat-partner
		 liece-current-channel))
    (when chnl
      (save-excursion
	(run-hook-with-args 'liece-redisplay-buffer-functions chnl)))
    (liece-redisplay-unread-mark)
    (liece-configure-windows)))

(defsubst liece-channel-set-operator-1 (chnl user val)
  (let* ((chnl (intern chnl liece-obarray)) (opers (get chnl 'oper)))
    (if val
	(or (string-list-member-ignore-case user opers)
	    (put chnl 'oper (cons user opers)))
      (if (string-list-member-ignore-case user opers)
	  (put chnl 'oper (string-list-remove-ignore-case user opers))))))

(defsubst liece-channel-set-voice-1 (chnl user val)
  (let* ((chnl (intern chnl liece-obarray)) (voices (get chnl 'voice)))
    (if val
	(or (string-list-member-ignore-case user voices)
	    (put chnl 'voice (cons user voices)))
      (if (string-list-member-ignore-case user voices)
	  (put chnl 'voice (string-list-remove-ignore-case user voices))))))

(defun liece-channel-set-operator (chnl user val)
  (let ((nbuf (cdr (string-assoc-ignore-case chnl liece-nick-buffer-alist)))
	(xuser user))
    (liece-channel-set-operator-1 chnl user val)
    (liece-channel-set-voice-1 chnl user val)
    (setq user (concat (if val "@" " ") user)
	  xuser (concat (if val "[ +]" "@") (regexp-quote xuser)))
    (with-current-buffer nbuf
      (let (buffer-read-only)
	(goto-char (point-min))
	(liece-nick-replace xuser user nil t)))))

(defun liece-channel-set-voice (chnl user val)
  (let ((nbuf (cdr (string-assoc-ignore-case chnl liece-nick-buffer-alist)))
	(xuser user))
    (liece-channel-set-voice-1 chnl user val)
    (setq user (concat (if val "+" " ") user)
	  xuser (concat (if val " " "\\+") (regexp-quote xuser)))
    (with-current-buffer nbuf
      (let (buffer-read-only)
	(goto-char (point-min))
	(liece-nick-replace xuser user nil t)))))

(defun liece-channel-prepare-partner (join-channel-var)
  (setq liece-current-chat-partner
	(or liece-current-chat-partner join-channel-var))
  (let ((liece-command-buffer-mode 'chat))
    (liece-channel-join join-channel-var t))
  (liece-channel-change))

(defun liece-channel-buffer-invisible-p (chnl mode)
  (let ((cbuf (liece-pick-buffer chnl)))
    (or (liece-frozen (car cbuf))
	(and (eq mode 'chat)
	     (not (and (eq liece-command-buffer-mode 'chat)
		       liece-current-chat-partner
		       (string-equal-ignore-case
			chnl liece-current-chat-partner))))
	(not (and (eq liece-command-buffer-mode 'channel)
		  liece-current-channel
		  (string-equal-ignore-case
		   chnl liece-current-channel))))))

(defun liece-channel-prepare-representation (chnl &optional method name)
  (cond
   ((eq method 'dcc)
    (format liece-dcc-channel-representation-format chnl))
   (name
    (format liece-default-channel-representation-format name chnl))
   (t chnl)))

(defun liece-channel-parse-representation (str)
  (cond
   ((string-match
     (format
      (regexp-quote liece-dcc-channel-representation-format)
      "\\([^ ]+\\)")
     str)
    (vector 'dcc nil (match-string 1 str)))
   ((string-match
     (format
      (regexp-quote liece-default-channel-representation-format)
      "\\([^ ]+\\)" "\\([^ ]+\\)")
     str)
    (vector 'irc (match-string 1 str) (match-string 2 str)))
   (t (vector 'irc nil str))))

(defun liece-channel-list-add-button (n chnl)
  (insert (format "%2d: " n))
  (if liece-highlight-mode
      (let ((st (point)))
	(insert chnl)
	(liece-widget-convert-button
	 'liece-channel-push-button st (point) chnl))
    (insert chnl))
  (insert "\n"))

(defun liece-channel-add-buttons (start end)
  (save-excursion
    (goto-char start)
    (while (re-search-forward
	    (eval-when-compile
	      (concat "\\(^\\(" liece-time-prefix-regexp "\\)?"
		      "[][=<>(-][][=<>(-]?\\|\\s-+[+@]?\\)"
		      "\\([&#!%][^ :]*\\)"))
	    end t)
      ;;(re-search-forward "\\s-+\\(\\)\\([-+]\\S-*\\)" end t)
      (let* ((chnl-start (match-beginning 3))
	     (chnl-end (match-end 3))
	     (chnl (buffer-substring chnl-start chnl-end)))
	(when liece-highlight-mode
	  (liece-widget-convert-button
	   'liece-channel-push-button chnl-start chnl-end chnl))))))

;;;###liece-autoload
(defun liece-channel-redisplay-buffer (chnl)
  (let ((buffer
	 (cdr (string-assoc-ignore-case
	       chnl liece-channel-buffer-alist)))
	(window (liece-get-buffer-window liece-channel-buffer)))
    (when (liece-channel-unread-p chnl)
      (setq liece-channel-unread-list
	    (delete chnl liece-channel-unread-list))
      (run-hook-with-args 'liece-channel-read-functions chnl))
    (and buffer window
	 (with-current-buffer buffer
	   (set-window-buffer window buffer)
	   (unless (liece-frozen buffer)
	     (set-window-point window (point-max)))
	   (setq liece-channel-buffer buffer)))))

;;;###liece-autoload
(defun liece-channel-list-redisplay-buffer (chnl)
  (let ((window (liece-get-buffer-window liece-channel-list-buffer)))
    (when window
      (save-selected-window
	(select-window window)
	(goto-char (point-min))
	(search-forward chnl nil t)
	(set-window-point window (match-beginning 0))
	(when liece-highlight-mode
	  (let ((overlay (make-overlay (point)(match-end 0))))
	    (liece-map-overlays
	     (lambda (ovl)
	       (if (overlay-get ovl 'liece-channel)
		   (delete-overlay ovl))))
	    (overlay-put overlay 'face 'underline)
	    (overlay-put overlay 'liece-channel t)))))))

(provide 'liece-channel)

;;; liece-channel.el ends here
