#!/usr/bin/env python
#
###########################################
#
# Script for importing .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_csv -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
import settings
setup_environ(settings)
from gheat.models import *
import datetime
import csv

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

  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)

  csvfile = csv.reader(open(location, 'rb'), delimiter='\t')
  for row in csvfile:
    lat = row[0].replace('N ', '')
    lon = row[1].replace('E ', '')
    ssid = row[2].strip('( )')
    bssid = row[4].strip('( )')
    enc = row[8]
    enc = enc[2]
    sig = 100 # Get's fix soon
    print lat, lon, ssid, bssid, enc, sig

    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=sig)


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'])
