#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
###########################################
#
# Script for importing DroidStumbler .csv files
#
# In theory, only the -f option is needed, but for overview's sake, please use the others aswell.
# -f = location of the .netxml, e.g. '/home/test.csv'
# -m = name of the dataset, e.g. 'Walk in park' or 'Trip with boat'
# -g = your name
# -e = your email address
#
# (Run from project root)
# ./manage.py import_droidstumbler -f <file location> -m <dataset name> -g <username> -e <email>
#
# Make sure the variables in this script match the column numbers in your file e.g.;
# Lat is read from the first column [0], if the lat in your file is in the 4th column, change
# 'lat = row[0]' to 'lat = row[3]'.
# Also, take note of the 'replace()' and 'strip()' functions. These should probably be edited aswell.
#
# Dennis Wagenaar
# d.wagenaar@gmail.com
#
###########################################

from django.core.management import setup_environ
from django.core.management.base import BaseCommand
from optparse import OptionParser, make_option
from gheat.models import *
import datetime
import csv

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

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

  csvfile = csv.reader(open(location, 'rb'), delimiter=',')
  for row in csvfile:
    epoch, msg_type, lat, lon, accuracy, ssid, bssid, level, frequency, capabilities, empty = row
    if msg_type == "data" and lat and lon:
      ap, created = Accespoint.objects.get_or_create(mac=bssid, ssid=ssid, encryptie=capabilities)
      if created:
        print "# INFO: New AccessPoint %s (%s)" % (ap.ssid, ap.mac)
      m = Meting.objects.create(meetrondje=mr, accespoint=ap, latitude=lat, longitude=lon, signaal=(100 + int(level)))
      print "# INFO: New Meeting: %s" % m

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_droidstumbler(options['location'],options['meetrondje'],options['gebruiker'],options['email'])
