# -*- coding: utf-8 -*-
#
# UnivNautes
# Copyright (C) 2014  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.core.management.base import BaseCommand, CommandError

import os
import sys
import shutil
from sp import pfconfigxml
import urllib2
import json
import math

from authentic2.saml.models import LibertyProvider
from django.conf import settings
from sp import pfconfigxml

GEOINFOS_JS = os.path.join(settings.STATIC_ROOT, 'univnautes', 'geoinfos.js')

def laxfloat(x):
    try:
        return float(x)
    except:
        return 666

class Command(BaseCommand):
    help = 'build geoinfo.js from UnivNautes/pfSense config.xml geo URLs'

    def handle(self, *args, **options):
        idps = {}

        sp = pfconfigxml.get_sp()
        for url in sp.get('ui', {}).get('geolocations', []):
            try:
                print 'download geo locations from %s' % str(url)
                geolist = json.load(urllib2.urlopen(url))
            except urllib2.HTTPError as e:
                print 'Error loading JSON data source (%s)' % str(e)
            except urllib2.URLError as e:
                print 'Error loading JSON data source (%s)' % str(e)
            except ValueError as e:
                print 'Error reading JSON data source output (%s)' % str(e)
            else:
                for idp in geolist:
                    entityid = idp.get('entityID')
                    if not entityid:
                        # idp with no entityID ?... just ignore
                        continue
                    geos = idp.get('geo')
                    if not geos:
                        print 'warn: no geo info for %s' % entityid
                        continue
                    if isinstance(geos, dict):
                        geos = [geos]
                    dots = set()
                    for geo in geos:
                        if not isinstance(geo, dict) \
                                or not 'lat' in geo \
                                or not 'lon' in geo:
                            print 'warn: geo is not a lat/lon dict for %s' % entityid
                            continue
                        dots.add((laxfloat(geo['lat']), laxfloat(geo['lon'])))
                    if entityid not in idps:
                        idps[entityid] = dots
                    else:
                        idps[entityid].update(dots)

        geoinfos = []

        n = 0
        for idp in LibertyProvider.objects.all():
            if idp.entity_id in idps:
                geos = list(idps[idp.entity_id])
            else:
                # print 'idp %s do not have geo, randomize it' % idp.entity_id
                geos = [(47.0+2.0*math.sin(n), 2.5+3.0*math.cos(n))]
                n += 1
            geoinfos.append({
                'slug': idp.slug,
                'name': idp.name,
                'entityid': idp.entity_id,
                'geo': geos
            })

        tempfilename = '/var/tmp/univnautes-geoinfo.js-%s' % os.getpid()

        with open(tempfilename, 'wb') as f:
            f.write('geoinfos = ')
            json.dump(geoinfos, f, indent=2)
            f.write('\n')

        shutil.move(tempfilename, GEOINFOS_JS)

