# http file response
# (c) 2007, RePa

from django.http import HttpResponse, Http404
import mimetypes
import os.path
from Cookie import SimpleCookie

class HttpFileResponse(HttpResponse):
  """
  a special file based HTTP response
  the whole file isn't read into the memory for performance reasons
  """

  def __init__(self, filename, mimetype=None, chunksize=65536):
    # check if the file exists
    if not os.path.isfile(filename):
      # return 404
      HttpResponse.__init__(self, content='Not found!', mimetype='text/plain')
      self.status_code = 404

    if not mimetype:
      mimetype = str(mimetypes.guess_type(filename)[0])

    self._is_string = False

    self.headers = {
        'Content-Type': mimetype, 
        'Content-Length': str(os.path.getsize(filename)),
        'Content-Description': 'File Transfer',
        'Content-Disposition': 'attachment; filename='+os.path.basename(filename),
        }
    self.cookies = SimpleCookie()
    self.status_code = 200
    self.filename = filename
    self.chunksize = chunksize

  def _set_content(self, filename):
    """
    set the new filename
    """
    if not os.path.isfile(filename):
      return

    mimetype = str(mimetypes.guess_type(filename)[0])
    self.headers['Content-Type'] = mimetype
    self.headers['Content-Length'] = str(os.path.getsize(filename))
    self.headers['Content-Description'] = 'File Transfer'
    self.headers['Content-Disposition'] = 'attachment; filename='+os.path.basename(filename)
    self.status_code = 200
    self.filename = filename

  def _get_content(self):
    """
    don't return the full content, only the filename
    """
    return self.filename

  content = property(_get_content, _set_content)

  def __iter__(self):
    self._iterator = self._get_iterator()
    return self

  def close(self):
    try:
      self.file.close()
    except:
      pass

  def next(self):
    return self._iterator.next()

  def _get_iterator(self):
    """
    output iterator
    reads the file
    """
    # open file
    self.file = open(self.filename, 'rb')
    while 1:
      # read chunk size of data
      data = self.file.read(self.chunksize)
      # TODO: bandwidth control
      if len(data) > 0:
        yield data
      else:
        break
    self.file.close()


def teszt(request):
  filename = "/home/repa/proba.avi"
  response = HttpFileResponse(filename)

  return response


