from django import forms
from django.conf import settings
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.core.files.base import ContentFile
from django.db import IntegrityError
from django.http import HttpResponse,HttpResponseServerError
from django.shortcuts import render_to_response
from gheat.models import *

def get_apperatuur_choices(item):
  return sorted(set(Apparatuur.objects.values_list(item,item)))

class MeetBestandForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField()
    naam = forms.ChoiceField(choices=Gebruiker.objects.values_list('naam','naam'))
    kaart = forms.ChoiceField(choices=get_apperatuur_choices('kaart'))
    antenne = forms.ChoiceField(choices=get_apperatuur_choices('antenne'))
    surveyid = forms.CharField()
    bestand = forms.FileField()

#
# curl -Fusername=huub -Fpassword=bert -F naam=huub -F kaart=onbekend -F antenne=onbekend -F bestand=@manage.py -F surveyid=kerk http://localhost:8000/wlheatmap/add/meetbestand/
def add_meetbestand(request):
  if request.method == 'POST':
    form = MeetBestandForm(request.POST, request.FILES)
    if form.is_valid():
      username = form.cleaned_data['username']
      password = form.cleaned_data['password']
      user = authenticate(username=username, password=password)
      if user == None or not user.is_active:
        return HttpResponseServerError('ERROR: Authentication Failed')

      login(request, user)

      gebruiker = Gebruiker.objects.get(naam=form.cleaned_data['naam'])
      apparatuur, created = Apparatuur.objects.get_or_create(kaart=form.cleaned_data['kaart'],
        antenne=form.cleaned_data['antenne'])
      meetrondje, created = MeetRondje.objects.get_or_create(gebruiker=gebruiker,
        datum=None,
        naam=(form.cleaned_data['surveyid']),
        apparatuur=apparatuur)

      meetbestand, created = MeetBestand.objects.get_or_create(meetrondje=meetrondje,is_imported=False)
      if created:
        meetbestand.bestand.save(form.cleaned_data['bestand'].name,form.cleaned_data['bestand'])
        meetbestand.save()
        return HttpResponse('OK: Attached to meetrondje %s' % meetrondje)
      else:
        return HttpResponseServerError('ERROR: File does already exists')
    else:
      return HttpResponseServerError('ERROR: No valid input')
  else:
    form = MeetBestandForm()
  return render_to_response('add_file.html', {'form': form})

