from django.shortcuts import render_to_response
from django.http import HttpResponse,HttpResponseServerError
from django.conf import settings
from gheat.models import *
from django.db import IntegrityError

import gheat.dataimport
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

def js_layer_base(request):
  return render_to_response('js/LayerBase.js', {'settings' : settings },
    mimetype='application/javascript')

def process(request):
  response = HttpResponse()
  ch = logging.StreamHandler(stream=response)
  ch.setLevel(logging.DEBUG)
  formatter = logging.Formatter('%(levelname)-6s - %(name)-20s - %(message)s')
  ch.setFormatter(formatter)
  logging.getLogger().addHandler(ch)
  
  response.write('<pre>')
  for f in MeetBestand.objects.filter(is_imported=False):
    logger.info("%s | %s", f.bestand.name, f.meetrondje)
    try:
      gheat.dataimport.import_file(f.bestand.path, f.meetrondje)
    except IntegrityError, e:
      logger.error(e)
      continue
    f.is_imported = True
    f.save()
  response.write('</pre>')
  return response

from django import forms
from django.core.files.base import ContentFile

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

class MeetBestandForm(forms.Form):
    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'))
    bestand = forms.FileField()

#
# curl  -F naam=huub -F kaart=onbekend -F antenne=onbekend -F bestand=@manage.py http://localhost:8000/wlheatp/add/meetbestand/
def add_meetbestand(request):
  if request.method == 'POST':
    form = MeetBestandForm(request.POST, request.FILES)
    if form.is_valid():
      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['bestand']),
        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')
      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})
