#!/usr/bin/python

# based on the intro of chapter 13 in the cookbook
#
# wgetk7.py is a modified version of wget.py
# modified 10/17/20 to work with pythos 3 instead of python 2
#
# This script retrieves the current image from the NOAA web site.

import getopt
import sys
import urllib
import urllib.request
import os
from datetime import datetime, date, time, timedelta
import time

BUFSIZE = 8192

# rate limit in bytes per second
ratelimit = 5000.0
stars = '*' * 100

def slowly(blk, bs, size):
    global name
    #time.sleep (bs/ratelimit)
    perc = (blk * 100.0 * bs) / size
    sys.stdout.write ("\r%s: %-100s %3.2f%%" % (name, stars[:int (perc)], perc))
    sys.stdout.flush ()

# Python cookbook 14.6
class Getcont (urllib.request.FancyURLopener):
    def http_error_206 (self, url, fp, errcode, errmsg, headers, data = None):
        pass
    
def main (lst):
    global outname
    global passwd
    outname = passwd = None
    
    #opts, args = getopt.getopt (lst, ":o:p")
    #if len (args) < 1:
    #    print "Usage: wget [-o name] [-p passwd] url ..."
    #    sys.exit (1)
    #for opt, val in opts:
    #    if opt == "-o":
    #        outname = val
    #    elif opt == "-p":
    #        passwd = val
    #for name in args:
    #    url = name.strip()
    #    all below indented to this level, except last line in script
    
    # url = 'http://thunderstorm.vaisala.com/explorer_files/lts-image.jpg'
    
    upath="https://services.swpc.noaa.gov/images/"
    ufname="station-k-index"
    ufext=".png"
    url = upath + ufname + ufext
        
    print(url)
    
    # get UTC time
    # (for date and time to append to image file name)
    now = datetime.utcnow() - timedelta(0,0,0,0,0,0,0) # days, s, us, ms, m, h, w offset
    fdate=now.strftime("%Y%m%d")
    ftime=now.strftime("%H%M")
    
    name = "k-index_7-day_" + fdate + ufext
    getcont = Getcont ()
    stime = None
            
    inf = getcont.open (url)
    tsize = int(inf.headers["Content-Length"])
            
    if tsize < 1000:
     print(name, "unavailable or doesn't exist.")
     inf.close ()
    else:
     if os.path.exists (name):
        outf = open (name, "ab")
        cursize = os.path.getsize (name)
        if tsize == cursize:
            print(name, "already fully retrieved.")
            inf.close ()
            outf.close ()
            return
        print("continuing from", cursize)
        getcont.addheader ("Range", "bytes=%s-" % cursize)
     else:
        outf = open (name, "wb")
        cursize = 0

     print("%s: %d kB" % (name, tsize / 1000))
     isize = cursize
     while True:
        data = inf.read (BUFSIZE)
        if not data:
            break
        outf.write (data)
        rate = ""
        left = tsize - cursize
        cursize += len (data)
        if stime:
            dt = time.time () - stime
            if dt > 5:
               rate = (cursize - isize) / dt
               eta = int (left / rate)
               min, sec = divmod (eta, 60)
               rate = "%3.1f kB/s ETA %d:%02d  " % (rate / 1000.0, min, sec)
        else:
            stime = time.time ()
        #time.sleep (bs/ratelimit)
        perc = (cursize * 100.0) / tsize
        sys.stdout.write ("\r%-50s %3.2f%% %s" % \
                       (stars[:int (perc / 2)], perc, rate))
        sys.stdout.flush ()
     print()  
      
if __name__ == "__main__":
    main (sys.argv[1:])
    
