# Create your views here.
from django.shortcuts import render_to_response, get_object_or_404
from models import *
from django.template import RequestContext
from django.http import HttpResponse
from os.path import join, exists
from settings import STATIC_ROOT, STATIC_URL, MEDIA_ROOT, MEDIA_URL
from sorl.thumbnail import get_thumbnail
import Image

def render_page(request, slug):
    page = get_object_or_404(ContentPage, slug=slug)
#    try:
#        page = ContentPage.objects.get(slug=slug)
#    except:
#        page = get_object_or_404(CoursePage, slug=slug)        
    context = RequestContext(request, {'page': page.get_dict(), 'pageObject': page})
    return render_to_response(page.template_name, context)


#def markitup_image_upload(request, default_width=350, max_width=900):
#    #get vars
#    fil = request.FILES['miu_image_upload_image']
#    name = fil.name
#    width = request.POST.get('miu_image_width', default_width)

#    #validate is an image
#    try:
#        i = Image.open(fil)
#    except: #if not image, treat as file FIXME
#        destPath = join(MEDIA_ROOT, "markitup_file_uploads/%s" % name)
#        if not exists(destPath):
#            with open(destPath, "wb+") as destination:
#                for chunk in fil.chunks():
#                    destination.write(chunk)        
#        return HttpResponse(destPath.replace(MEDIA_ROOT, MEDIA_URL))

#    #validate width value, set to default / max
#    try:
#        widthInt = int(width.strip())
#    except:
#        widthInt = default_width
#    if widthInt > max_width:
#        widthInt = max_width
#    widthStr = str(widthInt)

#    #get destination path
#    destPath = join(MEDIA_ROOT, "markitup_image_uploads/%s" % name)
#    if not exists(destPath):
#        with open(destPath, "wb+") as destination:
#            for chunk in fil.chunks():
#                destination.write(chunk)
##    foo = open(destPath)
#    thumb = get_thumbnail(open(destPath), widthStr).url   
#    return HttpResponse(thumb)
