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

from collections import defaultdict

logger = logging.getLogger(__name__)

def process_netxml(fh,counters):
  try:
    netxml_doc = etree.parse(fh)
  except etree.XMLSyntaxError, e:
    raise IOError(e)

  # Prepare new accesspoints and measurements
  wnetworks = netxml_doc.findall('wireless-network')

  # Temponary holders
  ap_pool = {}
  client_pool = {}

  # Create all accesspoints and for caching validation purposes store them
  # locally as well
  for wnetwork in wnetworks:
    bssid = wnetwork.find('BSSID').text
    ap_type = wnetwork.attrib['type']
    # Only access points and clients (for ignore listings)
    if ap_type in ['infrastructure', 'data']:
      counters['ap_total'] += 1
      encryption = (wnetwork.find('SSID/encryption') != None)
      ssid_node = wnetwork.find('SSID/essid[@cloaked="false"]')
      ssid = ssid_node.text if ssid_node != None else 'hidden'

      ap_pool[bssid] = (ssid, encryption)
    elif ap_type in ['probe', 'ad-hoc']:
      counters['client_total'] += 1
      client_pool[bssid] = True
    else:
      logger.error('Unknown type %s - %s',bssid, wnetwork.attrib['type'])

  return (counters, ap_pool, None, None)



def process_gpsxml(fh,counters):
  try:
    gpsxml_doc = etree.parse(fh)
  except etree.XMLSyntaxError, e:
    raise IOError(e)

  bssid_failed = defaultdict(int)

  # Prepare new accesspoints and measurements
  points = gpsxml_doc.findall('gps-point')

  # Temponary holders
  meting_pool = defaultdict(list)

  for point in points:
    counters['meting_total'] += 1
    #XXX: This needs to be either the 'bssid' or the 'source', 
    #XXX: accesspoint from or too data.
    bssid = point.attrib['bssid']
    # XXX: Filter this in the beginning with XPath, but etree does not support
    # that (yet).
    if bssid in ['GP:SD:TR:AC:KL:OG','00:00:00:00:00:00']:
      counters['meting_ignored'] =+ 1
      continue
    # XXX: Signal need properly be a relation of signal_dbm and noice_dbm
    try:
      level = point.attrib['signal_dbm']
    except KeyError:
      logger.debug("Point '%s' does not have signal strengh" % point)
      counters['meting_failed'] += 1
      continue
    # We store all values found, avg or max will be done later on
    key = (bssid, point.attrib['lat'], point.attrib['lon'])
    signaal=100 + int(level)
    meting_pool[key].append(signaal)
  return (counters, None, None, meting_pool)
