;;; File:
;;;   newgreeting.ss
;;; Version:
;;;   1.2 of 11 February 2003
;;; Author:
;;;   Samuel A. Rebelsky
;;; Contents:
;;;   A simple example of some Scheme procedures for CGI.  Essentially,
;;;   a version of greeting.ss with all the helper procedures put in
;;;   a separate library and the testing value removed.  This version
;;;   will also generate its own form if you don't provide the user's
;;;   name.
;;; Organization:
;;;   Preparation - Stuff I need to do to get started
;;;   Page Generators - Procedures for generating specific kinds of
;;;     pages (when given particular values)
;;;   Interface - Stuff to extract important values and then
;;;     call the page generators.  You'll find (page) here.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Preparation

;;; Look!  We're going to use Sam's CGI library.  What fun.
(load "/home/rebelsky/Web/Scheme/webutils.ss")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Page Generators

;;; Procedure
;;;   greeting-page
;;; Parameters:
;;;   name, a string
;;; Purpose:
;;;   Generates an HTML page that can greet the named person.
;;; Produces:
;;;   A string that corresponds to that page.
;;; Preconditions:
;;;   The string must be nonempty.
;;; Postconditions:
;;;   The returned page is valid HTML.
(define greeting-page
  (lambda (name)
    (make-page 
      (head (string-append "A page for " name))
      (body (string-append
              (heading 1 "Scheme Salutes You")
              (string #\newline)
              (paragraph (string-append "Hello " name "!")))))))

;;; Procedure
;;;   greeting-form
;;; Parameters:
;;;   [None]
;;; Purpose:
;;;   Generates an HTML page for an input form for this CGI script.
;;; Produces:
;;;   A string that corresponds to that page.
;;; Preconditions:
;;;   [None]
;;; Postconditions:
;;;   The returned page is valid HTML.
(define greeting-form
  (lambda ()
    (make-page 
      (head "Enter Your Name")
      (body (form "newgreeting.cgi"
                  "Please enter your name and click me!"
                  (textfield "user" ""))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Interface

;;; Procedure:
;;;   page
;;; Parameters:
;;;   None
;;; Purpose:
;;;   Builds an HTML page according to specifications.
;;; Produces:
;;;   A string that corresponds to the HTML page.
;;; Preconditions:
;;;   greeting-page must be defined, take one parameter, and generate a page.
;;;   greeting-form must be defined.
;;; Postconditions:
;;;   The returned page is as valid as anything greeting-page or
;;;   greeting-form produces.
(define page
  (lambda ()
    (page-helper (get-cgi-variable 'user ""))))

  (define page-helper
    (lambda (person)
      (if (string=? person "") ; Default value indicates no param
          (greeting-form)
          (greeting-page person))))
