from django.shortcuts import get_object_or_404, render_to_response
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from models import MultiuploaderImage
from django.core.files.uploadedfile import UploadedFile
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile

from django.core.urlresolvers import reverse
import base64
import shutil
import os


#importing json parser to generate jQuery plugin friendly json response
from django.utils import simplejson

#for generating thumbnails
#sorl-thumbnails must be installed and properly configured
from sorl.thumbnail import get_thumbnail


from django.views.decorators.csrf import csrf_exempt

from itsapp.debug import *
import itsapp.ITSconf 

import logging
log = logging


@csrf_exempt
def multiuploader_delete(request, pk):
    """
    View for deleting photos with multiuploader AJAX plugin.
    made from api on:
    https://github.com/blueimp/jQuery-File-Upload
    """
    if request.method == 'POST':
	path=default_storage.path(base64.b16decode(str(pk)))
        print('Called delete image. image '+path)
	try:
        	os.remove(path)
	except Exception as expt:
		print expt
        print('DONE. Deleted photo id='+str(pk))
        return HttpResponse(str(pk))
    else:
        print('Received not POST request to delete image view')
        return HttpResponseBadRequest('Only POST accepted '+pk)

@csrf_exempt
def multiuploader(request):
    """
    Main Multiuploader module.
    Parses data from jQuery plugin and makes database changes.
    """
    if request.method == 'POST':
        print('received POST to main multiuploader view')
        if request.FILES == None:
            return HttpResponseBadRequest('Must have files attached!')

        #getting file data for farther manipulations
        file = request.FILES[u'files[]']


	path= default_storage.save('upload_imgs/'+request.user.username+'/'+file.name, ContentFile(file.read()))
	print "save done ("+path+")"
	abspath = settings.MEDIA_ROOT+path
	PHOTO_MAX_SIZE="1200"
	print "resize (max "+PHOTO_MAX_SIZE+")"
	os.system("convert -resize "+PHOTO_MAX_SIZE+"X"+PHOTO_MAX_SIZE+"\> \""+abspath+"\" \""+abspath+"\"")
	print "resize done"
 	

	thumb_url="nourl"#reverse("get_thumb_data",args=[str(base64.b16encode(abspath)),80])

        file_delete_url ="nourl"#reverse("multi_delete",args=[base64.b16encode(path)]) #settings.MULTI_FILE_DELETE_URL+'/'+base64.b16encode(path)
        file_url = "no_url"#settings.MULTI_IMAGE_URL+'/'+image.key_data+'/'


        #generating json response array
        result = []
	result.append({"name":file.name, 
                       "size":file.size, 
                       "url":"no_url", 
                       "thumbnail_url":thumb_url,
                       "delete_url":file_delete_url, 
                       "delete_type":"POST",})

        response_data = simplejson.dumps(result)
        
        #checking for json data type
        #big thanks to Guy Shapiro
        if "application/json" in request.META['HTTP_ACCEPT_ENCODING']:
            mimetype = 'application/json'
        else:
            mimetype = 'text/plain'
	print('--------------------------------')
        return HttpResponse(response_data, mimetype=mimetype)
    else: #GET
        return HttpResponse('Only POST accepted')

def multi_show_uploaded(request, key):
    """Simple file view helper.
    Used to show uploaded file directly"""
    image = get_object_or_404(MultiuploaderImage, key_data=key)
    url = settings.MEDIA_URL+image.image.name
    return render_to_response('multiuploader/one_image.html', {"multi_single_url":url,})
