#!/usr/bin/env python
from django.core.management import setup_environ
from django.core.management.base import BaseCommand
from optparse import OptionParser, make_option
import settings
setup_environ(settings)
from gheat.models import *
from lxml import etree
import datetime

def import_file(location, meetrondje, gebruiker, email):

  datasource = etree.parse(location)
  doc = datasource.findall('wireless-network')

  g, created = Gebruiker.objects.get_or_create(naam=gebruiker , email=email)
  a, created = Apparatuur.objects.get_or_create(antenne='test' , kaart='test')
  mr = MeetRondje.objects.create(datum=datetime.datetime.now() , naam=meetrondje , gebruiker=g , apparatuur=a)

  for wnetwork in doc:
    enc = wnetwork.find('SSID/encryption')
    if enc != None: enc = 'true'
    else: enc = 'false'
    ssid = wnetwork.find('SSID/essid')
    if ssid != None: ssid = ssid.text
    else: ssid = 'hidden'
    bssid = wnetwork.find('BSSID')
    if bssid != None: bssid = bssid.text
    lat = wnetwork.find('gps-info/min-lat')
    if lat != None: lat = lat.text
    lon = wnetwork.find('gps-info/min-lon')
    if lon != None: lon = lon.text
    if ssid is None: continue
    print enc, ssid, bssid, lat, lon 

    ap, created = Accespoint.objects.get_or_create(mac=bssid, ssid=ssid, encryptie=enc)
    m = Meting.objects.create(meetrondje=mr, accespoint=ap, latitude=lat, longitude=lon, signaal=100)


class Command(BaseCommand):
  option_list = BaseCommand.option_list + (
    make_option('-f', '--location', dest='location', default='location'),
    make_option('-m', '--meetrondje', dest='meetrondje', default='rondje'),
    make_option('-g', '--gebruiker', dest='gebruiker', default='username'),
    make_option('-e', '--email', dest='email', default='foo@bar.org'),
    )

  def handle(self, *args, **options):
    import_file(options['location'],options['meetrondje'],options['gebruiker'],options['email'])
