#!/usr/bin/python3

import pprint
import time
import sys
import os
import gzip
import requests
import requests.auth
import json
import subprocess
from urllib.request import urlopen

import ExceptionHandler 

natsUrl = "https://www.nats.aero/"
pibUrl = "https://pibs.nats.co.uk/operational/pibs/PIB.xml"
fileName = time.strftime("PIB-%Y%m%d.xml.gz")

def timestamp():
        return(time.strftime("%a %d/%m/%Y %H:%M:%S"))


def getFile():
        user = "akmoore"
        pwd = "Zaph@d123456"

        try:
                print("%s: Logging into NATS: %s" % (timestamp(), natsUrl))
                chargerSession = requests.Session()
                chargerSession.auth = requests.auth.HTTPDigestAuth(user, pwd)
                response = chargerSession.get(natsUrl)

                print("%s: Logged into NATS.  Getting file: %s" % (timestamp(), pibUrl))
                response = chargerSession.get(pibUrl)
                print("%s: Response: %s" % (timestamp(), response))

                print("%s: Writing data to %s" % (timestamp(), fileName))
                with gzip.open(fileName, "w") as tmpF:
                        tmpF.write(("%s" % (response.text)).encode("utf-8"))
        except Exception as exc:
                print(ExceptionHandler.FullStack(sys.exc_info()))
                return None

        return

getFile()

