#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Rick van der Zwet <info@rickvanderzwet.nl>
#
import csv
import logging

from collections import defaultdict

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

def process_csv(fh, counters):
  """ Import all points, return tuple with summary"""

  # Temponary holders
  meting_pool = defaultdict(list)
  ap_pool = {}

  csvfile = csv.reader(fh, delimiter=',')
  # Process file, preparing new access points and measurements
  for row in csvfile:
    try:
      epoch, msg_type, lat, lon, accuracy, ssid, bssid, level, frequency, capabilities = row
      bssid = bssid.upper()
    except ValueError:
      # Known error, please ignore
      if row[1] == 'gps' and len(row) == 12: continue
      logger.error("Unable to parse line:%i '%s'" % (csvfile.line_num, row))
      continue
    if msg_type == "data" and lat and lon:
      counters['meting_total'] += 1
      if not ap_pool.has_key(bssid):
        encryption = 'WPA' in capabilities or 'WEP' in capabilities
        ap_pool[bssid] = (ssid, encryption)

      # We store the best value found
      key = (bssid, lat, lon)
      signaal=(100 + int(level))
      meting_pool[key].append(signaal)

  return (counters, ap_pool, None, meting_pool)
