#!/usr/bin/env python

'''
output a merge of idp + geo informations from discojuice
'''

# initialise django environnement for pffedportal
# (the script is launched into the pffedportal directory)
import os
os.environ['DJANGO_SETTINGS_MODULE'] = "settings"

from authentic2.saml.models import LibertyProvider
from xml.etree import ElementTree as ET
from operator import itemgetter
import sys
import json
import math
import urllib

def geo2idp(filename):
    idps = {}
    try:
        f = open(filename)
    except IOError, e:
        print >> sys.stderr, e
        return {}
    try:
        idp_list = json.load(f)
    except ValueError, e:
        f.close()
        print >> sys.stderr, 'reading %s: %s' % (filename, e)
        return {}
    f.close()
    if not idp_list:
        return {}
    if not isinstance(idp_list, list):
        print >> sys.stderr, '%s does not contain a list' % filename
        return {}
    for idp in idp_list:
        try:
            idps[idp['entityID']] = idp
        except Exception, e:
            print >> sys.stderr, 'bad geo information in %s (%s)' % (filename, idp)
    return idps

geo_idps = {}
for geofile in sys.argv[1:]:
    geo_idps.update(geo2idp(geofile))


def get_ui_displayname(provider):
    def get_first_child(xml, child):
        for c in xml:
            if c.tag.endswith(child):
                return c
        return None
    xml = ET.fromstring(provider.metadata.encode('utf-8'))
    for tag in ('IDPSSODescriptor', 'Extensions', 'UIInfo', 'DisplayName'):
        xml = get_first_child(xml, tag)
        if xml is None:
            return provider.name
    return xml.text


n = 0
idps = []
for provider in LibertyProvider.objects.all():
    n += 1
    geo = geo_idps.get(provider.entity_id, {}).get('geo',
            {'lat': 47.0+2.0*math.sin(n), 'lon': 2.5+3.0*math.cos(n)})
    idps.append({
        'entityid': provider.entity_id,
        'name': get_ui_displayname(provider),
        'lat': geo['lat'],
        'lon': geo['lon'],
        'href': '/sso?' + urllib.urlencode([('entity_id', provider.entity_id)]),
    })

print """{% extends "login0.html" %}
{% block idps %}"""

for idp in sorted(idps, key=itemgetter('name')):
    li = u'<li><a href="%(href)s" class="idplink" ' \
            'data-lat="%(lat)s" data-lon="%(lon)s" ' \
            'data-entityid="%(entityid)s" ' \
            'data-filtertext="%(name)s">%(name)s</a></li>' % idp
    print li.encode("utf-8")

print "{% endblock %}"

