#lang racket/base
; Helpers to simplify the writing of weblets

(require
  web-server/http
  web-server/http/redirect
  net/url-string
  xml
  "http-message.rkt"
  "weblet-parameter.rkt")

(provide
  apply-or-return
  raw-data-weblet
  html-page-weblet
  redirect-to-https-weblet)

; Apply or return - If value is a procedure, apply it to the request, or else return value
(define (apply-or-return value param)
  (if (procedure? value)
      (value param)
      value))

; Weblet to return raw data
(define (raw-data-weblet
          #:body body ; body, as a bytes-string or a procedure taking the request and returning a bytes-string
          #:content-type [content-type #"text/plain;charset=utf-8"] ; type of the content, as a bytes-string
          #:error-code [error-code 200] ; page error code
          #:headers [headers (list)] ; headers of the response, or a procedure taking the request and returning the list of headers
        )
  (lambda (param)
    (response/full
      error-code (http-message error-code)
      (current-seconds)
      content-type
      (apply-or-return headers param)
      (list
        (apply-or-return body param)))))

; Weblet to return html data
(define (html-page-weblet
          #:body body ; body, as an xexpr or a procedure taking the request and returning an xexpr
          #:error-code [error-code 200] ; page error code
          #:headers [headers (list)] ; headers of the response, or a procedure taking the request and returning the list of headers
        )
  (lambda (param)
    (response/full
      error-code (http-message error-code)
      (current-seconds)
      TEXT/HTML-MIME-TYPE
      (apply-or-return headers param)
      (list
        (string->bytes/utf-8
          (xexpr->string
            (apply-or-return body param)))))))

; Weblet to redirect to https, same place, same method
(define redirect-to-https-weblet
  (lambda (param)
    (define uri (request-uri (weblet-parameter-request param)))
    (define new-uri
      (make-url
        "https"
        (url-user uri)
        (url-host uri)
        (url-port uri)
        (url-path-absolute? uri)
        (url-path uri)
        (url-query uri)
        (url-fragment uri)))
    (redirect-to
      (url->string new-uri)
      temporarily/same-method)))
