(use-modules (alterator glob))

(define *system-backend2-dir* "/usr/lib/alterator/backend2/")
(define *system-backend3-dir* "/usr/lib/alterator/backend3/")
(define *cache* (make-hash-table 10))

(define (get-value cmd name value)
  (if (woo-error? cmd)
      value
      (woo-get-option cmd name value)))

(define (extract-description language)
  (lambda (name)
    (let* ((short-name (substring name (string-length "template-")))
           (cmd (cond-car (woo "info" name 'language language)))
           (title (get-value cmd 'title short-name))
           (group (get-value cmd 'group title))
           (description (get-value cmd 'description title))
           (weight (get-value cmd 'weight 0))
           (skip (get-value cmd 'skip #f)))
      (and (not skip)
           (list short-name
                 'title title
                 'weight weight
                 'group group
                 'description description
                 'weight weight)))))

(define (template-backends)
  (delete-duplicates
   (map basename
        (append
         (glob (string-append *system-backend2-dir* "template-*"))
         (glob (string-append *system-backend3-dir* "template-*"))))))

(define (template<=? x y)
  (> (woo-get-option x 'weight) (woo-get-option y 'weight)))

(define (fill-cache language)
  (let ((value  (sort (filter-map (extract-description language)
                                  (template-backends))
                      template<=?)))
    (hash-set! *cache* language value)
    value))

(define (info-list options)
  (let ((language (cond-plistq 'language options '("en_US"))))
     (or (hash-ref *cache* language)
         (fill-cache language))))

(object
 #f
  ((constraints self objects options)
   (let ((_ (make-translator "alterator-fbi" (cond-plistq 'language options '()))))
     `(title (label ,(_ "Title"))
       description (label ,(_ "Description")))))
  ((read self objects options)
   (cond-assoc (cond-car objects) (info-list options) '()))
  ((list self objects options)
   (info-list options)))

  
        
