
(require 'custom)

(defcustom work-list-dir 
  (expand-file-name "~/.work-list")
  "Directory to store work-lists in"
  :group 'work-list
  :type '(directory))
(defvar work-list-history nil
  "The buffers that contains work-lists")
(defvar work-list-current (format-time-string "%Y-%m.work")
  "The current work-list")
(defvar work-list-text-history nil
  "History og work-list texts")

(defun work-list-file-name (list)
  (concat work-list-dir "/" list))
(defun work-list (list &optional not-current)
  (let ((file-name (work-list-file-name list)))
    (let ((buffer (find-file-noselect file-name)))
      (if (not not-current)
          (set 'work-list-current list)))))
(defun work-list-time-format (time)
  (format-time-string "%Y-%m-%d %H:%M:%S" time))


(defun work-list-entry (hours time text list)
  (let ((when-string (if (stringp time)
                         time
                       (work-list-time-format time)))
        (hour-string (if (not (or (floatp hours) (integerp hours)))
                         (error "hours given is not a number: %S" hours)
                       (format "%2f" hours)))
        (text-string text))
    (save-excursion
      (set-buffer (work-list list))
      (goto-char (point-max))
      (insert "*** " when-string ": " hour-string "\n" text-string "\n")
      (save-buffer)
      t)))

(defun work-list-read-buffer nil
  (read-from-minibuffer "work-list: " work-list-current nil nil work-list-history))
(defun work-list-read-time nil
  (let ((cur-time (work-list-time-format (current-time))))
    (read-from-minibuffer "date: " cur-time nil nil nil cur-time)))
(defun work-list-read-hours nil
  (float (read-from-minibuffer "hours: " nil nil t)))
(defun work-list-read-text nil
  (read-from-minibuffer "text: " nil nil nil work-list-text-history))

(defun work-list-enter (&optional hours time text list)
  (interactive)
  (let* ((buf (or list (work-list-read-buffer)))
         (tm (or time (work-list-read-time)))
         (h (or hours (work-list-read-hours)))
         (txt (or text (work-list-read-text))))
    (work-list-entry h tm txt buf)))

(defun work-list-quick-entry (hours)
  (interactive "Phours: ")
  (work-list-enter hours (current-time) nil work-list-current))

(defun work-list-setup-keys nil
  (global-set-key [(control ?c) ?w ?q] 'work-list-quick-entry)
  (global-set-key [(control ?c) ?w ?e] 'work-list-enter))

(work-list-setup-keys)

