def download_helper():
    '''Download a fresh consensus doc at interval according
    to dir-spec.

    We need this helper to do thread-safe things with twisted.
    '''
    global consensus

    while True:
        current_time = Com.get_current_time()
        fresh_until = Com.date_to_timestamp(str(consensus.fresh_until))
        print current_time, fresh_until
        print 'sleeping for ' + str(fresh_until - current_time)
        time.sleep(fresh_until - current_time)
        print 'waking up'
        d = DocDownloader()
        d.get_consensus()
        consensus = d.consensus
        current_time = Com.get_current_time()
        fresh_until = Com.date_to_timestamp(str(consensus.fresh_until))
        print current_time, fresh_until
        print 'sleeping for ' + str(fresh_until - current_time)
        time.sleep(fresh_until - current_time)
        print 'waking up'
        d = DocDownloader()
        d.get_consensus()
        consensus = d.consensus


def get_initial_consensus():
    '''Get a fresh consensus when we first start up.
    '''
    d = DocDownloader()
    d.get_consensus()
    return d.consensus

consensus = get_initial_consensus()

reactor.callFromThread(download_helper)
reactor.run()
     
if __name__ == '__main__':
    #d = DocDownloader()
    #d.get_consensus()
    current_time = Com.get_current_time()
    fresh_until = Com.date_to_timestamp(str(consensus.fresh_until))
    print current_time, fresh_until
    print 'sleeping for ' + str(fresh_until - current_time)