(use-modules (alterator http template)
             (alterator http html)

             (alterator configd html)
             (alterator configd woo)
             (alterator configd form)
             (alterator configd constraints)
             (alterator configd frontend))

(define (main-args url url-args)
  (let ((args (woo-args url url-args)))
    (or (find (lambda(arg) (string=? url (car arg))) args)
        (car (woo-args url (list  (assoc "language" url-args)))))))

(define (form url action url-args template-args)
  (let ((redirect (cond-assq 'redirect template-args url))
        (url-redirect (cond-assoc 'url-redirect template-args #f))
        (async (cond-assoc "async" url-args)))
    (cond
     (url-redirect
      (html:redirect url-redirect))
     ((string=? action "read")
      (let ((args (main-args url url-args)))
        (template (design-path (cond-assoc 'url template-args "form-unknown.html"))
                  (apply fill-constraints "write" args)
                  (apply fill-form args))))
     (else
      (for-each
       (lambda(cmd)
         (apply (if (string=? action "delete") woo-try woo-try/constraints)
                action cmd))
       (woo-args url url-args))
      (if (or (not redirect) async)
          (form url "read" url-args template-args)
          (html:redirect redirect))))))

(lambda (self objects options)
  (let ((url (string-append "/" (string-join objects "/")))
        (url-args (cond-plistq 'url-args options))
        (template-args (cond-plistq 'template-args options))
        (action (cond-plistq 'action options)))
    (list
     'scm
     (woo-catch
      (thunk (form url action url-args template-args))
      (lambda(reason)
        (html:error (form url "read" url-args template-args) reason))))))
