;;; 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
   (eval-when-compile
     (concat "^" liece-channel-regexp))
   chnl))

(defun liece-channel-modeless-p (chnl)
  (string-match
   (eval-when-compile
     (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))

;;; Internal functions
(defun liece-channel-remove (chnl chnls)
  "Remove CHNL from CHNLS."
  (remove-if
   (lambda (item)
     (and (stringp item) (liece-channel-equal chnl item)))
   chnls))

(defun liece-channel-delete (chnl chnls)
  "Delete CHNL from CHNLS."
  (delete-if
   (lambda (item)
     (and (stringp item) (liece-channel-equal chnl item)))
   chnls))

(defmacro liece-channel-set-topic (topic &optional chnl)
  "Set CHNL or current channels's topic."
  `(put (intern (or ,chnl liece-current-channel) liece-obarray)
	'topic ,topic))

(defmacro liece-channel-add-mode (mode &optional chnl)
  "Add MODE as char to CHNL."
  `(let ((modes (liece-string-to-list (or (liece-channel-get-modes ,chnl)
					 ""))))
     (or (memq ,mode modes)
	 (push ,mode modes))
     (put (intern (or ,chnl liece-current-channel) liece-obarray)
	  'mode (mapconcat #'char-to-string modes ""))))

(defmacro liece-channel-remove-mode (mode &optional chnl)
  "Remove MODE as char to CHNL."
  `(let ((modes (liece-string-to-list (or (liece-channel-get-modes ,chnl)
					 ""))))
     (delq ,mode modes)
     (put (intern (or ,chnl liece-current-channel) liece-obarray)
	  'mode (mapconcat #'char-to-string modes ""))))

(defmacro liece-channel-set-mode (val mode &optional chnl)
  "Set character VAL as channel MODE into the CHNL."
  `(if val
       (liece-channel-add-mode ,mode ,chnl)
     (liece-channel-remove-mode ,mode ,chnl)))

(defmacro liece-channel-add-ban (pattern &optional chnl)
  "Add ban PATTERN as char to CHNL."
  `(let ((patterns (liece-channel-get-bans ,chnl)))
     (or (string-list-member-ignore-case ,pattern patterns)
	 (push ,pattern patterns))
     (put (intern (or ,chnl liece-current-channel) liece-obarray)
	  'ban patterns)))

(defmacro liece-channel-remove-ban (pattern &optional chnl)
  "Remove ban PATTERN as char to CHNL."
  `(let ((patterns (remove-if (lambda (elm) (string-equal ,pattern elm))
			      (liece-channel-get-bans ,chnl))))
     (put (intern (or ,chnl liece-current-channel) liece-obarray)
	  'ban patterns)))

(defmacro liece-channel-set-ban (chnl pattern val)
  "Set ban PATTERN as char to CHNL."
  `(if val
       (liece-channel-add-ban ,pattern ,chnl)
     (liece-channel-remove-ban ,pattern ,chnl)))

(defmacro liece-channel-add-exception (pattern &optional chnl)
  "Add exception PATTERN as char to CHNL."
  `(let ((patterns (liece-channel-get-exceptions ,chnl)))
     (or (string-list-member-ignore-case ,pattern patterns)
	 (push ,pattern patterns))
     (put (intern (or ,chnl liece-current-channel) liece-obarray)
	  'exception patterns)))

(defmacro liece-channel-remove-exception (pattern &optional chnl)
  "Remove exception PATTERN as char to CHNL."
  `(let ((patterns (remove-if (lambda (elm) (string-equal ,pattern elm))
			      (liece-channel-get-exceptions ,chnl))))
     (put (intern (or ,chnl liece-current-channel) liece-obarray)
	  'exception patterns)))

(defmacro liece-channel-set-exception (chnl pattern val)
  "Set exception PATTERN as char to CHNL."
  `(if val
       (liece-channel-add-exception ,pattern ,chnl)
     (liece-channel-remove-exception ,pattern ,chnl)))

(defmacro liece-channel-add-invite (pattern &optional chnl)
  "Add invite PATTERN as char to CHNL."
  `(let ((patterns (liece-channel-get-invites ,chnl)))
     (or (string-list-member-ignore-case ,pattern patterns)
	 (push ,pattern patterns))
     (put (intern (or ,chnl liece-current-channel) liece-obarray)
	  'invite patterns)))

(defmacro liece-channel-remove-invite (pattern &optional chnl)
  "Remove invite PATTERN as char to CHNL."
  `(let ((patterns (remove-if (lambda (elm) (string-equal ,pattern elm))
			      (liece-channel-get-invites ,chnl))))
     (put (intern (or ,chnl liece-current-channel) liece-obarray)
	  'invite patterns)))

(defmacro liece-channel-set-invite (chnl pattern val)
  "Set invite PATTERN as char to CHNL."
  `(if val
       (liece-channel-add-invite ,pattern ,chnl)
     (liece-channel-remove-invite ,pattern ,chnl)))
  
(defun liece-channel-virtual (chnl)
  "Convert channel name into internal representation.
\(For example if CHNL is a string \"#...:*\", it will be converted into
\"%...\"\)"
  (let ((mapping liece-channel-conversion-map) match)
    (while mapping
      (if (string-equal-ignore-case (caar mapping) chnl)
	  (setq match (cdar mapping)))
      (pop mapping))
    (if match
	match
      (save-match-data
	(cond
	 ((and (string-match "^[#+]\\(.*\\):\\(.*\\)$" chnl)
	       (string= (match-string 2 chnl)
			liece-channel-conversion-default-mask))
	  (if (eq ?+ (aref chnl 0))
	      (concat "-" (match-string 1 chnl))
	    (concat "%" (match-string 1 chnl))))
	 ((string= "" chnl) chnl)
;	 ((eq ?! (aref chnl 0))
;	  (concat "!" (substring chnl (1+ liece-channel-id-length))))
	 (t chnl))))))

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

;;;###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
