#!/usr/bin/env python3
import time
import requests
import horetu

url = 'https://wifigw.cis.vutbr.cz/login.php'
headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
}

def status():
    '''
    Check whether you are connected to the internet.
    '''
    r = requests.get(url, headers=headers)
    connected = 'input type="password"' not in r.text
    return {True:'connected', False:'not connected'}[connected]

def connect():
    '''
    Connect to the internet.
    '''
    requests.post(url, headers=headers,
                  data='user=pycon&auth=any&password=pycon2015cz')

def disconnect():
    '''
    Disconnect from the internet.
    '''
    requests.post(url, headers=headers, data='logout=1')

def watch(n=60, verbose=False):
    '''
    Poll the internet connection periodically, and reconnect if the
    connection is down.

    :param n: Seconds to sleep
    '''
    while True:
        try:
            s = status()
            if verbose:
                print(s)
            if s == 'not connected':
                connect()
            time.sleep(n)
        except KeyboardInterrupt:
            break

def main():
    horetu.cli([connect, disconnect, status, watch])

if __name__ == '__main__':
    main()
