# Create your views here.
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from models import GalleryAlbum, GalleryItem, Photo, GalleryLink, YoutubeVideo
from django.contrib.contenttypes.models import ContentType
from django.views.decorators.csrf import csrf_exempt
from django import forms
from ox.django.shortcuts import render_to_json_response
from sorl.thumbnail import get_thumbnail

def add(request, ctype_id, object_id):
    ctype = get_object_or_404(ContentType, pk=ctype_id)
    model_class = ctype.model_class()
    obj = get_object_or_404(model_class, pk=object_id)
    #FIXME: check permissions
    d = {
        'title': 'New Album',
        'content_type': ctype,
        'object_id': obj.id
    }
    gallery = GalleryAlbum(**d)
    gallery.save()
    return HttpResponseRedirect(gallery.get_edit_url())


def edit(request, id):
    gallery = get_object_or_404(GalleryAlbum, pk=id)
    photos = Photo.objects.filter(album=gallery)
    youtube_videos = YoutubeVideo.objects.filter(album=gallery)
    links = GalleryLink.objects.filter(album=gallery)
    context = RequestContext(request, {
        'gallery': gallery,
        'photos': photos,
        'links': links,
        'youtube_videos': youtube_videos
    })
    return render_to_response("mediagallery/upload.html", context)


def view(request, id):
    gallery = get_object_or_404(GalleryAlbum, pk=id)
    return render_to_response("mediagallery/view.html", gallery.get_dict())


def edit_title(request, id):
    gallery = get_object_or_404(GalleryAlbum, pk=id)
    title = request.GET.get("title", "")
    if title.strip() == '':
        return render_to_json_response({'error': 'Title is empty!'})
    gallery.title = title
    gallery.save()
    return render_to_json_response({'success': 'true'})


def edit_photo(request, id):
    item = get_object_or_404(Photo, pk=id)
    title = request.GET.get("title", "")
    if title.strip() == '':
        return render_to_json_response({'error': 'Title is empty!'})
    item.title = title
    item.save()
    return render_to_json_response({'success': 'true'})
 

#FIXME: check permissions
def delete_photo(request, id):
    item = get_object_or_404(Photo, pk=id)
    item.delete()
    return render_to_json_response({'success': 'true'})        


def add_youtube(request, id):
    gallery = get_object_or_404(GalleryAlbum, pk=id)
    url = request.GET.get("url", None)
    if not url:
        return render_to_json_response({'error': 'No URL supplied'})
    youtube_id = url.replace("http://youtu.be/", "")
    
    # info = youtube.info(youtube_id)
    yt = YoutubeVideo(album=gallery)
    yt.youtube_id = youtube_id
    yt.title = "fixme"

    yt.save()    
    return render_to_json_response({
        'id': yt.id,
        'title': yt.title,
        'thumbnail': yt.thumbnail() 
    })


def delete_youtube(request, id):
    video = get_object_or_404(YoutubeVideo, pk=id)
    video.delete()
    return render_to_json_response({'success': 'true'})


def add_link(request, id):
    gallery = get_object_or_404(GalleryAlbum, pk=id)    
    url = request.GET.get("url", None)
    title = request.GET.get("title", url)
    if not url:
        return render_to_json_response({'error': 'No URL supplied'})
    link = GalleryLink(album=gallery)
    link.url = url
    link.title = title
    link.save()
    return render_to_json_response({
        'id': link.id,
        'title': title,
        'url': url
    })

def delete_link(request, id):
    link = get_object_or_404(GalleryLink, pk=id)
    link.delete()
    return render_to_json_response({'success': 'true'})


@csrf_exempt
def upload(request):
    if request.method == 'POST':
        if request.POST.get('name', False):
            
            id = request.POST.get("id", 0)
            album = GalleryAlbum.objects.get(pk=id)
            name = request.POST.get("name", "untitled")
            item = Photo(title=name, album=album)
            item.save()
            response = {
                'result': 1,
                'maxRetry': 10,
                'uploadUrl': '/mediagallery/' + str(item.id) + '/chunk'
            }
            return render_to_json_response(response)
    return HttpResponse("error!")


class ChunkForm(forms.Form):
    chunk = forms.FileField()
    done = forms.IntegerField(required=False)

@csrf_exempt
def chunk(request, id):
    if request.method == 'POST':
        response = {}
        item = get_object_or_404(Photo, id=id)
        form = ChunkForm(request.POST, request.FILES)
        canEdit = True #FIXME check for permissions
        if form.is_valid() and canEdit:
            f = form.cleaned_data['chunk']
            if item.title:
                name = item.title
            else:
                name = f.name
#            if extFileName(name).lower() in ['jpg', 'jpeg', 'png']:
#              thumbnail = get_thumbnail(
            if not item.save_chunk(f.read(), name):
                response['result'] = 'failed'
            elif form.cleaned_data['done']:
                item.done = True
                item.save()
                response = {
                  'resultUrl': '/files/' + str(item.id),
                  'id': item.id,
                  'title': name,
                  #'type': item.type,
                  'thumbnail': get_thumbnail(item.image, "100x100", crop="center").url
                }

                response['done'] = 1
                response['result'] = 1
            else:
                response['result'] = 1
            return render_to_json_response(response)
    response = {
        'result': -1,
        'fileUrl': '/'
    }
    return render_to_json_response(response)




'''
def edit_gallery(request):
    context = RequestContext(request, {})
    return render_to_response("mediagallery/upload.html", context)
'''

