from django.core.context_processors import csrf
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, render_to_response
from django.template import Template, Context
from django.views.decorators.csrf import csrf_exempt
from sharenews.models import *
from itertools import chain
from time import time
import django.utils.simplejson as json;
import datetime
import base64
import cStringIO
import PIL.Image

####################################           WEB           ####################################

# Crea la vista de la pagina d'inici
def home(request):
    noticies = Noticia.objects.order_by('id').reverse()
    if request.user.is_authenticated():
        profileDataProfile = request.user.userprofile
    return render(request,'home.html', locals())

# Comprova si l'usuari existeix
@csrf_exempt
def checkUsername(request):
    success = False
    if request.method != 'POST':
        return HttpResponseRedirect('/')
    elif request.method == 'POST':
        username = request.POST.get('username', None)
        if User.objects.filter(username=username).exists():
            success = False
        else:
            success = True
    ajax_vars = {'success': success}
    return HttpResponse(json.dumps(ajax_vars), mimetype='application/javascript')

# Crea un nou comentari
def comment(request):
    if request.method == 'POST':
        contingut = request.POST['contingut']
        noticia = Noticia.objects.get(id=request.POST['noticia'])
        instance = Comentari(noticia = noticia, contingut = contingut, autor = request.user)
        instance.save()
        profileDataProfile = request.user.userprofile
        profileDataProfile.num_comentaris += 1
        profileDataProfile.save()
        return HttpResponseRedirect('/read/'+str(noticia.id)+'/#comments') # Redirect after POST
    else:
        return render(request, 'home.html', locals())

# Crea una nova noticia
def compose(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        titol = request.POST['titol']
        contingut = request.POST['contingut']
        categoria = request.POST['categoria']
        tags = request.POST['tags']
        localitzacio = request.POST['localitzacio']
        geolatitud = request.POST['geolatitud']
        geolongitud = request.POST['geolongitud']
        instance = Noticia(titol = titol, contingut = contingut, tags = tags, categoria = categoria, autor = request.user, localitzacio = localitzacio, geolatitud = geolatitud, geolongitud = geolongitud)
        instance.save()
        medialist = request.POST['medias']
        if (medialist != ''):
            medialist = medialist.split(',')
            for median in medialist:
                instance.media.add(median)
        profileDataProfile = request.user.userprofile
        profileDataProfile.num_noticies += 1
        profileDataProfile.save()
        return HttpResponseRedirect('/read/'+str(instance.id)) # Redirect after POST
    else:
        return render(request, 'compose.html', locals())

# Actualitza les dades de l'usuari
def editprofile(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        request.user.first_name = request.POST['fname']
        request.user.last_name = request.POST['lname']
        request.user.email = request.POST['email']
        profileDataProfile = request.user.userprofile
        profileDataProfile.biografia = request.POST['biografia']
        profileDataProfile.website = request.POST['website']
        profileDataProfile.localitzacio = request.POST['localitzacio']
        request.user.save()
        profileDataProfile.save()
        return HttpResponseRedirect('/profile/') # Redirect after POST
    else:
        return HttpResponseRedirect('/')

# Crea la pagina Error 404
def error404(request):
    return render(request,'404.html')

# Penja un arxiu
@csrf_exempt
def uploadfile(request):
    if request.method == 'POST':
        media = request.FILES['upl']
        instance = Media(file = media, autor = request.user)
        instance.save()
        extension = instance.file.name.split('.')[-1]
        if extension == 'mov' or extension == 'mp4':
            instance.isvideo = True
            instance.save()
            profileDataProfile = request.user.userprofile
            profileDataProfile.num_videos += 1
            profileDataProfile.save()
        else:
            profileDataProfile = request.user.userprofile
            profileDataProfile.num_fotos += 1
            profileDataProfile.save()
        ajax_vars = {'success': 'success' }
    else:
        ajax_vars = {'success': 'error'}
    return HttpResponse(json.dumps(ajax_vars), mimetype='application/javascript')

# Penja una nova foto de perfil
@csrf_exempt
def fileProfile(request):
    if request.method == 'POST':
        media = request.FILES['upl']
        profileDataProfile = request.user.userprofile
        profileDataProfile.picture = media
        profileDataProfile.save()
        ajax_vars = {'success': 'success' }
    else:
        ajax_vars = {'success': 'error'}
    return HttpResponse(json.dumps(ajax_vars), mimetype='application/javascript')

# Retorna l'ultim arxiu penjat per l'usuari
@csrf_exempt
def lastMedia(request):
    if request.method == 'POST':
        username = request.user.id
        medias = Media.objects.filter(autor_id=username).latest('data')
        ajax_vars = {'success': 'success', 'medias': medias.id }
    else: 
        ajax_vars = {'success': 'error' }
    return HttpResponse(json.dumps(ajax_vars), mimetype='application/javascript')

# Connecta a l'usuari
def loginPage(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            # the password verified for the user
            if user.is_active:
                login(request, user)
                print("User is valid, active and authenticated")
            else:
                print("The password is valid, but the account has been disabled!")
        else:
            # the authentication system was unable to verify the username and password
            print("The username and password were incorrect.")
    return home(request)

# Desconnecta a l'usuari
def logoutPage(request):
    logout(request)
    print("User is valid, active and authenticated")
    return HttpResponseRedirect('/') # Redirect after POST

# Mostra el mapa
def mapa(request):
    noticies = Noticia.objects.order_by('id').reverse()
    return render(request, 'map.html', locals())

# Mostra noticies d'una categoria
def category(request, category):
    noticies = Noticia.objects.filter(categoria__icontains=category).order_by('id').reverse()
    if request.user.is_authenticated():
        profileDataProfile = request.user.userprofile
    return render(request,'home.html', locals())

# Mostra el propi perfil d'usuari
def myprofile(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')
    profileData = request.user
    profileDataProfile = request.user.userprofile
    noticies = Noticia.objects.filter(autor=request.user).order_by('id').reverse()
    medias = profileData.media_set.all().order_by('id').reverse()
    return render(request, 'profile.html', locals())

# Mostra un perfil d'usuari
def profile(request, username):
    profileData = User.objects.get(username=username)
    profileDataProfile = profileData.userprofile
    noticies = Noticia.objects.filter(autor=profileData).order_by('id').reverse()
    medias = profileData.media_set.all().order_by('id').reverse()
    return render(request, 'profile.html', locals())

# Mostra una noticia per llegir
def read(request, newsid):
    newsData = Noticia.objects.get(id=newsid)
    medias = newsData.media.all()
    noticies = Noticia.objects.filter(id=newsid)
    comentaris = Comentari.objects.filter(noticia_id=newsid).order_by('id').reverse()
    return render(request, 'read.html', locals())

# Crea un nou usuari i el connecta
def register(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        fname = request.POST['fname']
        lname = request.POST['lname']
        username = request.POST['username']
        email = request.POST['email']
        password = request.POST['password']
        password2 = request.POST['password2']
        condicions = request.POST['condicions']
        user = User.objects.create_user(username, email, password)
        user.first_name = fname
        user.last_name = lname
        user.save()
        userL = authenticate(username=username, password=password)
        login(request, userL)
        userP = UserProfile(user = user)
        userP.save()
        return HttpResponseRedirect('/profile') # Redirect after POST
    else:
        return render(request, 'register.html', locals())

# Mostra les noticies amb tags determinats
@csrf_exempt
def search(request):
    noticies = Noticia.objects.order_by('id').reverse()
    tags = request.GET.get('t').split(',');
    for tag in tags:
        noticies = noticies.filter(tags__icontains=tag)
    if request.user.is_authenticated():
        profileDataProfile = request.user.userprofile
    return render(request,'home.html', locals())

# Calcula la nova puntucio de la noticia
def vote(request):
    if request.method == 'POST':
        noticia = Noticia.objects.get(id=request.POST['noticia'])
        votacionsNova = noticia.votacions + 1
        puntuacioNova = ((noticia.puntuacio*(noticia.votacions)) + float(request.POST['punts'])) / votacionsNova
        noticia.puntuacio = puntuacioNova
        noticia.votacions = votacionsNova
        noticia.save()
        return HttpResponseRedirect('/read/'+str(noticia.id)) # Redirect after POST
    else:
        return render(request, 'home.html', locals())

def mailuser(request):
    send_mail('Email de prova', 'Example content of email', 'ShareNews', ['tfgsharenews@gmail.com'])
    return HttpResponse('Email')

####################################         ANDROID         ####################################

@csrf_exempt
def loginPageAndroid(request):

    f = open('/var/lib/openshift/531dc037e0b8cd47ec000164/app-root/repo/wsgi/sharenews/sharenews/workfile.txt', 'w')
    writetext = 'Comensa el loginPageAndroid,' + '<br>'
    f.write(writetext)
        
    data=json.loads(request.body)
    f.write(str(request.body))
    f.write(str(data))
    username= data['user']
    password = data['password']
    response_data = {}
    f.write("avans")
    user = authenticate(username=username, password=password)
    f.write("despres")
    if user is not None:
        # the password verified for the user
        if user.is_active:
            login(request, user)
            response_data['result'] = '1'
            response_data['username'] = user.username
            f.write("User is valid, active and authenticated")
            print("User is valid, active and authenticated")
        else:
            response_data['result'] = '2'
            f.write("The password is valid, but the account has been disabled!")
            print("The password is valid, but the account has been disabled!")
    else:
        # the authentication system was unable to verify the username and password
        response_data['result'] = '3'
        f.write("The username and password were incorrect.")
        print("The username and password were incorrect.")


    
    return HttpResponse(json.dumps(response_data), content_type="application/json") 

@csrf_exempt
def afegirNoticia(request):
    noticia = Noticia(titol='R.titol',contingut= 'R.contingut',puntuacio = 1)
    noticia.save()
    print "afegirNoticia"
    response = "funcionaaa"
    llistaNoticies = Noticia.objects.all()
    for i in range(len(llistaNoticies)):
            response = str(response) + "<br>"  + str(llistaNoticies[i].id) + " - " + str(llistaNoticies[i].titol)
    f = open('/var/lib/openshift/531dc037e0b8cd47ec000164/app-root/repo/wsgi/sharenews/sharenews/workfile.txt', 'w')
    f.write('holaaa')
    f.close()
    return HttpResponse(response)


@csrf_exempt
def agafarMedia(request):
    f = open('/var/lib/openshift/531dc037e0b8cd47ec000164/app-root/repo/wsgi/sharenews/sharenews/workfile.txt', 'w')
    writetext = 'Comensa el degub agafar Media,' + '<br>'
    f.write(writetext)
    numero=12
    noticiaTornar = Noticia.objects.get(id=numero)
    f.write(str(noticiaTornar.id))
    cosa = noticiaTornar.media.all()
    f.write("//////////////////////")
    f.write(str(cosa))
    f.write("------------------")
    f.write(str(cosa))
    llistaMedia=[]
    for n in cosa:
        f.write("akiiii")
        url = n.file
        llistaMedia.append(url)
        f.write(str(url))
        f.write("------------------")
    
    
   
    
    f.write("sortiin")
    f.close()
  
    return HttpResponse(json.dumps(response_data), content_type="application/json")


@csrf_exempt
def llegirNoticies(request):
        f = open('/var/lib/openshift/531dc037e0b8cd47ec000164/app-root/repo/wsgi/sharenews/sharenews/workfile.txt', 'w')
        writetext = 'Comensa el degub llegir Noticies,' + '<br>'
        f.write(writetext)
        
        info = request.POST["numeroIdNoticia"]
        data = json.loads(info)
        numero = int(data["id"])
        f.write(str(numero))
        noticia = Noticia.objects.latest('id')
        ultimaNoticiaNumero = noticia.id
        f.write(str(ultimaNoticiaNumero))
        segueix= True
 
        while(segueix):
            f.write("while")
            if(numero <= ultimaNoticiaNumero):
                f.write("primer if")
                if (Noticia.objects.get(id=numero)):
                    f.write("segon if")
                    noticiaTornar = Noticia.objects.get(id=numero)
                    segueix = False
                else:
                    f.write("primer else")
                    numero= numero+1
            else:
                f.write("segon else")
                segueix=False

        f.write("marxan")
        # Tornar "NoticiaTornar"
        response_data = {}
        response_data['id'] = str(noticiaTornar.id)
        response_data['titol'] = noticiaTornar.titol
        response_data['contingut'] = noticiaTornar.contingut
        response_data['autor'] = noticiaTornar.autor.username
        response_data['tags'] = noticiaTornar.tags
        response_data['categories'] = noticiaTornar.categoria
        response_data['latitude'] = noticiaTornar.geolatitud
        response_data['longitude'] = noticiaTornar.geolongitud
        response_data['localitzacio'] = noticiaTornar.localitzacio
        response_data['data'] = str(noticiaTornar.data)
        f.close()
        #f.write("sortin conecta---   ")
        return HttpResponse(json.dumps(response_data), content_type="application/json")

@csrf_exempt
def llegirNoticiesBasic(request):
        f = open('/var/lib/openshift/531dc037e0b8cd47ec000164/app-root/repo/wsgi/sharenews/sharenews/workfile.txt', 'w')
        writetext = 'Comensa el degub llegir Noticies,' + '<br>'
        f.write(writetext)
        
        info = request.POST["numeroIdNoticia"]
        data = json.loads(info)
        numero = int(data["id"])
    
        for noti in Noticia.objects.all():
            if(noti.id == numero):
                noticiaTornar = noti
                

        response_data = {}
        if(noticiaTornar):
            response_data['resultat'] = "OK"
            response_data['id'] = str(noticiaTornar.id)
            response_data['titol'] = noticiaTornar.titol
            response_data['contingut'] = noticiaTornar.contingut
            response_data['autor'] = noticiaTornar.autor.username
            response_data['tags'] = noticiaTornar.tags
            response_data['categories'] = noticiaTornar.categoria
            response_data['latitude'] = noticiaTornar.geolatitud
            response_data['longitude'] = noticiaTornar.geolongitud
            response_data['localitzacio'] = noticiaTornar.localitzacio
            response_data['data'] = str(noticiaTornar.data)

            arxius = noticiaTornar.media.all()
            cadenaFotos=""
            cadenaVideos=""
            f.write("-----------------------------------")
            f.write(str(arxius))
            f.write("avans for///")
            if(str(arxius)!='[]'):
                for n in arxius:
                    url = n.file
                    if(n.isvideo==True):
                        f.write("dintre video///")
                        cadenaVideos=cadenaVideos+str(url)+","
                    else:
                        f.write("dintre foto///")
                        cadenaFotos=cadenaFotos+str(url)+","

                response_data['fotos'] = cadenaFotos
                response_data['videos'] = cadenaVideos
                f.write("despres for///")
            else:
                response_data['fotos'] = "missingFoto"
                response_data['videos'] = "missingVideo"
            
        else:
            response_data['resultat'] = "Error"
            
        f.close()
        return HttpResponse(json.dumps(response_data), content_type="application/json")

   
@csrf_exempt
def llegirNoticiesCategoriaBasic(request):
        f = open('/var/lib/openshift/531dc037e0b8cd47ec000164/app-root/repo/wsgi/sharenews/sharenews/workfile.txt', 'w')
        writetext = 'Comensa el degub llegir Noticies,' + '<br>'
        f.write(writetext)
        
        info = request.POST["numeroIdNoticia"]
        data = json.loads(info)
        category = data['categoriaBuscar']

        noticies = Noticia.objects.filter(categoria__contains=category).order_by('id').reverse()
        f.write("---------------------")
        f.write(str(noticies))
                
        f.write("---------------------")
        response_data = {}
        if(str(noticies)!='[]'):
            response_data['resultat'] = "OK"
            f.write("------------dintre if------------")
            c=0
            for noticiaTornar in noticies:
                f.write("------------dintre for--------------")
                response_data['id'+str(c)] = str(noticiaTornar.id)
                response_data['titol'+str(c)] = noticiaTornar.titol
                response_data['contingut'+str(c)] = noticiaTornar.contingut
                response_data['autor'+str(c)] = noticiaTornar.autor.username
                response_data['tags'+str(c)] = noticiaTornar.tags
                f.write("----------mitat-----------")
                response_data['categories'+str(c)] = noticiaTornar.categoria
                response_data['latitude'+str(c)] = noticiaTornar.geolatitud
                response_data['longitude'+str(c)] = noticiaTornar.geolongitud
                response_data['localitzacio'+str(c)] = noticiaTornar.localitzacio
                response_data['data'+str(c)] = str(noticiaTornar.data)

                arxius = noticiaTornar.media.all()
                cadenaFotos=""
                cadenaVideos=""
                f.write("-----------------------------------")
                f.write(str(arxius))
                f.write("avans for///")
                if(str(arxius)!='[]'):
                    for n in arxius:
                        url = n.file
                        if(n.isvideo==True):
                            f.write("dintre video///")
                            cadenaVideos=cadenaVideos+str(url)+","
                        else:
                            f.write("dintre foto///")
                            cadenaFotos=cadenaFotos+str(url)+","

                    response_data['fotos'+str(c)] = cadenaFotos
                    response_data['videos'+str(c)] = cadenaVideos
                    f.write("despres for///")
                else:
                    response_data['fotos'+str(c)] = "missingFoto"
                    response_data['videos'+str(c)] = "missingVideo"
                c=c+1
            response_data['numeroNoticies'] = str(c)
                
        else:
            f.write("-------------else-------------")
            response_data['resultat'] = "Error"
            
        f.close()
        return HttpResponse(json.dumps(response_data), content_type="application/json")

@csrf_exempt
def llegirNoticiesTagsBasic(request):
        f = open('/var/lib/openshift/531dc037e0b8cd47ec000164/app-root/repo/wsgi/sharenews/sharenews/workfile.txt', 'w')
        writetext = 'Comensa el degub llegir tags,' + '<br>'
        f.write(writetext)
        
        info = request.POST["numeroIdNoticia"]
        data = json.loads(info)
        tags = data['tagsBuscar']
        f.write(tags)
        f.write("---------")
        tags = tags.split(',');
        f.write(str(tags))
        tags.remove(' ')
        f.write(str(tags))
        noticies = Noticia.objects.order_by('id').reverse()

        for tag in tags:
            noticies = noticies.filter(tags__icontains=tag)

        f.write("--------------------")
        f.write(str(noticies))
        response_data = {}

        if(str(noticies)!='[]'):
            response_data['resultat'] = "OK"
            f.write("------------dintre if------------")
        c=0
        for noticiaTornar in noticies:
            f.write("------------dintre for--------------")
            response_data['id'+str(c)] = str(noticiaTornar.id)
            response_data['titol'+str(c)] = noticiaTornar.titol
            response_data['contingut'+str(c)] = noticiaTornar.contingut
            response_data['autor'+str(c)] = noticiaTornar.autor.username
            response_data['tags'+str(c)] = noticiaTornar.tags

            response_data['categories'+str(c)] = noticiaTornar.categoria
            response_data['latitude'+str(c)] = noticiaTornar.geolatitud
            response_data['longitude'+str(c)] = noticiaTornar.geolongitud
            response_data['localitzacio'+str(c)] = noticiaTornar.localitzacio
            response_data['data'+str(c)] = str(noticiaTornar.data)

            arxius = noticiaTornar.media.all()
            cadenaFotos=""
            cadenaVideos=""
            f.write("-----------------------------------")
            f.write(str(arxius))
            f.write("avans for///")
            if(str(arxius)!='[]'):
                for n in arxius:
                    url = n.file
                    if(n.isvideo==True):
                        f.write("dintre video///")
                        cadenaVideos=cadenaVideos+str(url)+","
                    else:
                        f.write("dintre foto///")
                        cadenaFotos=cadenaFotos+str(url)+","

                response_data['fotos'+str(c)] = cadenaFotos
                response_data['videos'+str(c)] = cadenaVideos
                f.write("despres for///")
            else:
                response_data['fotos'+str(c)] = "missingFoto"
                response_data['videos'+str(c)] = "missingVideo"
            c=c+1


        response_data['numeroNoticies'] = str(c)    
        f.close()
        return HttpResponse(json.dumps(response_data), content_type="application/json")

    
@csrf_exempt
def llegirComentarisBasic(request):
        f = open('/var/lib/openshift/531dc037e0b8cd47ec000164/app-root/repo/wsgi/sharenews/sharenews/workfile.txt', 'w')
        writetext = 'Comensa el degub llegir Comentaris basic,' + '<br>'
        #f.write(writetext)
        #f.write(str(request.POST))
        #f.write("SEPARACIO")

        info = request.POST["numeroIdNoticia"]
        data = json.loads(info)
        numero = int(data["id"])
        #f.write(str(numero))
        #f.write(str(type(numero)))
        #f.write("-------------------") 
        newsData = Noticia.objects.get(id=numero)
        #f.write(str(newsData))
        comentaris = Comentari.objects.filter(noticia_id=numero).order_by('id').reverse()
        #f.write("-------------------")
        response_data = {}

        if(str(comentaris)!='[]'):
            n=0
            #f.write("dintre if")
            #f.write(str(len(comentaris)))
            #f.write("----")
            response_data['resultat'] = "OK"
            for c in comentaris:
                #f.write("dintre for")
                #f.write("----")
                response_data['contingut'+str(n)] = str(c.contingut)
                
                response_data['autor'+str(n)] = str(c.autor)
                response_data['data'+str(n)] = str(c.data)
                n=n+1
            response_data['numeroComentaris'] = str(n)
            
        else:
            response_data['resultat'] = "Error"

        #f.write("SORTIN")
        f.close()
        return HttpResponse(json.dumps(response_data), content_type="application/json")

@csrf_exempt
def afegirComentari(request):
        f = open('/var/lib/openshift/531dc037e0b8cd47ec000164/app-root/repo/wsgi/sharenews/sharenews/workfile.txt', 'w')
        writetext = 'Comensa el degub afegir comentari,' + '<br>'
        f.write(writetext)
        f.write(str(request.POST))
        f.write("SEPARACIO")
       
        info = request.POST["infoNoticia"]
        
        data = json.loads(info)
        
       

        contingut = data['contingut']
        autor = data['autor']
        idNoticia = int(data['idNoticia'])

        f.write(str(idNoticia))
        
        user = User.objects.get(username=autor)
        f.write(str(user.username))
        noticia = Noticia.objects.get(id=idNoticia)
        instance = Comentari(noticia = noticia, contingut = contingut, autor = user)
        instance.save()

        f.write("SORTIN")
        f.close()
        
        response_data={}
        response_data['resultat'] = "OK"
  
        return HttpResponse(json.dumps(response_data), content_type="application/json")



@csrf_exempt
def afegirNoticiaGeri(request):
        
        
        f = open('/var/lib/openshift/531dc037e0b8cd47ec000164/app-root/repo/wsgi/sharenews/sharenews/workfile.txt', 'w')
        writetext = 'Comensa el degub afegir noticia Geri,' + '<br>'
        f.write(writetext)
        #f.write(str(request.POST))
        f.write("SEPARACIO")
       

        
        info = request.POST["infoNoticia"]
        #f.write(str(request.POST))
        data = json.loads(info)
        #data=json.loads(request.body)
        f.write(str(data))

        pallo = data['autor']
        titol='None'
        contingut='None'
        puntuacio=0
        autor=User.objects.get(username=pallo)
        f.write("despres pillar user")
        tags='None'
        categories='None'
        localitzacio='None'
        latitude=0.0
        longitude=0.0

        if "titol" in data:
            titol=str(data['titol'])
            f.write(str(titol))
        if "contingut" in data:
            contingut=str(data['contingut'])
            f.write(str(contingut))
        if "puntuacio" in data:
            puntuacio=int(data['puntuacio'])
            f.write(str(puntuacio))
        if "tags" in data:
            tags=str(data['tags'])
            f.write(str(tags))
        if "categories" in data:
            categoria=str(data['categories'])
            f.write(str(categoria))
        if "localitzacio" in data:
            localitzacio=str(data['localitzacio'])
            f.write(str(localitzacio))
        if "latitude" in data:
            latitude=float(data['latitude'])
            f.write(str(latitude))
        if "longitude" in data:
            longitude=float(data['longitude'])
            f.write(str(longitude))
        f.write("--------------------------")
        f.write("avams crear noticia")
        noticia = Noticia(titol=titol, contingut=contingut, puntuacio=puntuacio, autor=autor, tags=tags,categoria=categoria,localitzacio=localitzacio,geolatitud=latitude,geolongitud=longitude)
        f.write("despres crear noticia")
        noticia.save()    

        #f.write(str(request.FILES))
        
        try:
            if (("foto0" in request.FILES) or ("video0" in request.FILES)):
                f.write("dintre if///")
                for arxiu in request.FILES:
                    media = request.FILES[arxiu]
                    f.write("dintre for////")
                    f.write(str(arxiu))
                    if arxiu[0]=="v":
                        instance = Media(file=media, autor = autor, isvideo = True)
                        f.write("---if--")
                    else:
                        instance = Media(file=media, autor = autor)
                        f.write("---else--")
                        
                    instance.save()
                    noticia.media.add(instance)
        except:
            f.write("----------------- Fora ---------------")


        f.write("---SORTIN---")
        f.close()
        

        response_data = {}
        response_data['result'] = 'penjat amb exit'
        return HttpResponse(json.dumps(response_data), content_type="application/json")

@csrf_exempt
def conecta(request):
        f = open('/var/lib/openshift/531dc037e0b8cd47ec000164/app-root/repo/wsgi/sharenews/sharenews/workfile.txt', 'w')
        writetext = 'Comensa el degub,' + '<br>'
        f.write(writetext)
        f.write("dintre conecta---   ")
        response_data = {}
        response_data['result'] = 'ha entrat a la view conecta'
        response_data['message'] = 'You messed up'
        f.write("sortin conecta---   ")
        return HttpResponse(json.dumps(response_data), content_type="application/json")
