(import "persist")
(import "virtty")

(defclass <phone> (<dao-class>) ((name :accessor name)
                                 (number :accessor number)))
(defmethod initialize-object :after ((self <phone>) initargs)
   (setf (name self) (elt (content self) 0))
   (setf (number self) (elt (content self) 1))
   (setf (content self) nil))
(defmethod serialize ((obj <phone>))
   (list (name obj) (number obj)))
(defmethod key ((obj <phone>))
   (name obj))

(defun create-phone ()
   (let* ((vals (form "Create" '("Name" "Number")))
          (new-rec (create (class <phone>) 'c vals)))
         (insert-dao new-rec)))

(defun warn-no-rec ()
   (tynewline)
   (tyo "  ")
   (tyattrib t)
   (tyo "!!! RECORD NOT FOUND !!!")
   (tyattrib nil)
   (tybeep))

(defun retrieve ()
   (let* ((key (form "Retrieve" '("Name")))
          (rec (get-dao (class <phone>) (car key))))
         (if (null rec)
             (warn-no-rec)
             (print-form "Retrieve Result" '("Name" "Number") (serialize rec))))
   (tyflush)
   (tyi))

(defun update ()
   (let* ((key (form "Update" '("Name")))
          (old-rec (get-dao (class <phone>) (car key))))
         (if (null old-rec)
             (progn (warn-no-rec)
                    (tyflush)
                    (tyi))
             (let* ((vals (edit-form "Update Result" '("Name" "Number") (serialize old-rec)))
                    (new-rec (create (class <phone>) 'c vals)))
                   (update-dao new-rec)))))

(defun delete ()
   (let ((key (form "Delete" '("Name"))))
        (ndbm-delete (dynamic *db*) (car key))))

(defun main ()
   (typrologue)
   (dynamic-let ((*db* (ndbm-open "phone" (+ (ndbm-rdwr) (ndbm-creat)) #o644)))
            (let ((quitp nil))
                 (while (not quitp)
                        (case-using #'= (select "CRUD" '("Create" "Retrieve" "Update" "Delete" "Quit"))
                                    ((0) (create-phone))
                                    ((1) (retrieve))
                                    ((2) (update))
                                    ((3) (delete))
                                    ((4) (setq quitp t)))))
            (ndbm-close (dynamic *db*)))
   (tyepilogue))

;; (defglobal *x* (create (class <address>) 'n "Bane" 'p "12345"))
;; (insert-dao *x*)
;; (defglobal *y* (get-dao (class <address>) "Bane"))
