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
