#!/usr/bin/env python
# -*- coding: ISO-8859-1 -*-

from mod_python import psp


MAX_FILE_SIZE = 200000
REDIRECT = "http://a-k.homelinux.org/py/ip/ip2/2.2.2/2-2-2.py"

def index(req):
    """Takes request from browser. Runs webpage."""
    
    req.content_type = 'text/html; charset = utf-8'
    tmpl=psp.PSP(req, filename='2-2-2.html')
    tmpl.run()

def data(req):
    """Takes request from client. Checks the encoding from request."""
    
    
    # Checks the file stream if its not bigger than MAX_FILE_SIZE.
    # If it is to big run _file_to_big().
    
    if MAX_FILE_SIZE <= req.read_length:
        _file_to_big(req)
    else:   
        form = req.form['file']
        if len(form.value) > 0:
            enctype = {'text/plain': _enc_text,
                       'image/x-png': _enc_png,
                       'image/jpeg': _enc_jpeg}\
                               .get(form.type, _enc_default)(req, form)
        else:
            _empty_file(req)

def _file_to_big(req):
    """Internal function. Writes link to start page."""
    
    req.content_type = 'text/html; charset = utf-8'
    tmpl=psp.PSP(req, filename='error.html')
    tmpl.run(vars={'max': int(MAX_FILE_SIZE/1024)})
	
def _empty_file(req):
    """Internal function. If file is empty give link to start page."""
    
    req.content_type = 'text/html; charset = utf-8'
    tmpl=psp.PSP(req, filename='empty.html')
    tmpl.run()
	
def _write(req, content_type, filename, mime_type, size):
    """Internal function. Takes request, and four variables 
    and writes to client."""
    
    req.content_type = content_type
    req.write("FILENAME: " + filename + "\n")
    req.write("MIME TYPE: " + mime_type + "\n")
    req.write("SIZE: %d \n" %size)
	
def _enc_text(req, form):
    """Internal function. Takes request + variable. Then writes back to 
    client.
    """
    
    size = len(form.value)
    content_type = 'text/plain; charset = utf-8'
    _write(req, content_type, form.filename, form.type, size)
    req.write("Data: \n" + form.value + "\n")
	
def _enc_jpeg(req, form):
    """Internal function. Writes pictiure to client."""
    
    req.content_type = 'image/jpeg; charset = utf-8'
    req.write(form.value)

def _enc_png(req, form):
    """Internal function. Writes picture to client."""
    
    req.content_type = 'image/x-png; charset = utf-8'
    req.write(form.value)

def _enc_default(req, form):
    """Internal function that is the default. If no content-types are 
    matched they land here. Takes req + value. Sends it to _write().
    """
    
    size = len(form.value)
    content_type = 'text/plain; charset = utf-8'
    _write(req, content_type, form.filename, form.type, size)
