##############################################################################
# httphelper.py Version 0.0.1
# (c) by Michael Stroeder <michael@stroeder.com>
##############################################################################
# This module is distributed under the terms of the
# GPL (GNU GENERAL PUBLIC LICENSE) Version 2
# (see http://www.gnu.org/copyleft/gpl.html)
##############################################################################

import sys, time, msgzip

# Return seconds as RFC1123 Date/Time Format preferred
# in RFC2616 (HTTP 1.1)
def DateTimeRFC1123(secs=0):
  return time.strftime(
    '%a, %d %b %Y %H:%M:%S GMT',
    time.gmtime(secs)
  )

# Write HTTP-Header
def SendHeader(
  outf=sys.stdout,
  contenttype='text/html',
  charset='ISO-8859-1',
  contentlength='',
  expires_offset='',
  lastmodified='',
  additional_header = {}
):

  gzip = hasattr(outf,'fileobj')
  if gzip:
    headerf = outf.fileobj
  else:
    headerf = outf
 
  # Determine times
  gmt = time.time()
  if not lastmodified:
    lastmodified = DateTimeRFC1123(gmt)
  if not expires_offset:
    expires = DateTimeRFC1123(gmt)
  else:
    expires = DateTimeRFC1123(gmt+expires_offset)

  # Write header
  headerf.write('Content-Type: %s;charset=%s\r\n' % (contenttype,charset))
  if contentlength and not gzip:
    headerf.write('Content-Length: %s\r\n' % (contentlength))
  if gzip:
    headerf.write('Content-Encoding: gzip\r\n')
    headerf.write('Vary: Accept-Encoding\r\n')

  headerf.write('Last-Modified: %s\r\n' % (lastmodified))
  headerf.write('Expires: %s\r\n' % (expires))
  for h in additional_header.keys():
    headerf.write('%s: %s\r\n' % (h,additional_header[h]))
  # Write empty end-of-header line
  headerf.write('\r\n')
  headerf.flush()
  return


