#!/usr/bin/python
# Copyright European Organization for Nuclear Research (CERN)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Authors:
# - Joaquin Bogado, <jbogado@linti.unlp.edu.ar>, 2016
# - Mario Lassnig, <mario.lassnig@cern.ch>, 2016-2017

"""
Build the closeness for each link from AGIS.
"""

import datetime
import json
import requests

if __name__ == '__main__':

    RES = requests.get('http://atlas-agis-api.cern.ch/request/site/query/list_links/?json')

    if RES.ok:
        RESJ = json.loads(RES.text)
        DATA = {}
        for site in RESJ:
            if 'closeness' in site.keys():
                link = '%s:%s' % (site['src'], site['dst'])
                DATA[link] = {'closeness': {'latest': site['closeness'],
                                            'timestamp': datetime.datetime.utcnow().isoformat()[:-7]}}

        with open('/data/metrix/data/closeness-agis/closeness-agis-{0}.json'.format(datetime.datetime.utcnow().isoformat()[:-7]), 'w') as f:
            json.dump(DATA, f, indent=1, sort_keys=True)

        with open('/data/metrix/data/closeness-agis/latest.json', 'w') as f:
            json.dump(DATA, f, indent=1, sort_keys=True)

    else:
        print 'could not load json'
