#lang racket/base

; Output the notes into an 'extract' directory

(require
  "src/notepad/notes.rkt"
  "src/pages/notepad.rkt" ; To open the database
  "src/collection/tree.rkt"
  )

; Create the extract directory
(define extract-dir "notepad.extract")
(define (mkdirp path)
  (when (not (directory-exists? path))
        (make-directory path)))
(mkdirp extract-dir)

; Recursively extract all the notes from the tree of notes
(define (extract-note tr path)
  (define name (or (and (tree-value tr) (note-name (tree-value tr))) ""))
  (define page (string-append path "/" name ".page"))
  (define dir (string-append path "/" name))
  (when (tree-value tr)
        (define note (tree-value tr))
        (define file (open-output-file page #:exists 'truncate/replace))
        (fprintf file "@document~n")
        (fprintf file "[title:~a]~n" (note-title note))
        (fprintf file "[author:~a]~n" (note-author note))
        (fprintf file "[date:~a]~n" (note-date note))
        (fprintf file "{~n")
        (fprintf file "~a" (note-content note))
        (fprintf file "}~n")
        (close-output-port file))
  (define children (tree-children tr))
  (when (not (null? children))
        (mkdirp dir)
        (for-each
          (lambda (t)
            (extract-note t dir))
          children)))
(extract-note
  (note-list->tree (get-all-notes))
  extract-dir)
