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):
  def get_help_text(model, item):
    return "Reeds bekend: %s" % ','.join(model.objects.values_list(item,flat=True).distinct())
  username = forms.CharField()
  password = forms.CharField()
  naam = forms.CharField(help_text=get_help_text(Gebruiker, 'naam'))
  kaart = forms.CharField(help_text=get_help_text(Apparatuur, 'kaart'))
  antenne = forms.CharField(help_text=get_help_text(Apparatuur, 'antenne'))
  surveyid = forms.CharField(help_text=get_help_text(MeetRondje, 'naam'))
  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, created = Gebruiker.objects.get_or_create(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 %s does already exists' % meetbestand)
    else:
      return HttpResponseServerError('ERROR: No valid input')
  else:
    form = MeetBestandForm()
  return render_to_response('add_file.html', {'form': form})

