#!/usr/bin/python
try:
    import configparser
except ImportError:
    import ConfigParser as configparser

import os
from pprint import pprint
from textwrap import wrap
from datetime import datetime
from time import time
from json import loads
try:
    from urllib.parse import urlencode
    from urllib.request import urlopen
except ImportError:
    from urllib import urlencode,urlopen
from sys import argv, exit

config_path = os.path.join(os.path.expanduser('~'),'.bmndrrc')

Config = configparser.ConfigParser()
Config.read(config_path)

def ConfigSectionMap(section):
    dict1 = {}
    options = Config.options(section)
    for option in options:
        try:
            dict1[option] = Config.get(section, option)
            if dict1[option] == -1:
                DebugPrint("skip: %s" % option)
        except:
            print("exception on %s!" % option)
            dict1[option] = None
    return dict1

def time_to_days(dt):
    days = dt.days
    return '%sd' % days

try:
    auth_token = ConfigSectionMap('account')['auth_token']
except (KeyError, configparser.NoSectionError):
    print('Error: Missing or malformed configuration file.\n')
    print('Please go to https://www.beeminder.com/api/v1/auth_token.json')
    print('Then create a ~/.bmndrrc file like this:\n')

    print('[account]')
    print('auth_token: <your auth_token>')
    exit(1)

try:
    burner = ConfigSectionMap('account')['filter']
except (KeyError, configparser.NoSectionError):
    burner = 'frontburner'

# output for running "bmndr"
if len(argv) == 1:
    data = loads(urlopen('https://www.beeminder.com/api/v1/users/me/goals.json?auth_token=%s&filter=%s' % (auth_token,burner)).read().decode('utf-8'))

    parsed = sorted(data,key=lambda data:abs(data['losedate']))

    output = []
    for i in parsed:
        timeleft = datetime.fromtimestamp(int(i['losedate'])) - datetime.now()
        days = time_to_days(timeleft)
        line = ['$'+str(int(i['pledge'])),i['slug'],days,i['headsum']]
        output.append(line)
    col_width = max([len(i[1]) for i in output]) + 1
    for row in output:
        try:
            print(''.join((row[0].ljust(4),row[1].ljust(col_width),row[2].ljust(5),row[3])))
        except TypeError:
            pass

# output for running "bmndr <goal>"
elif len(argv) == 2:
    goal = argv[1]
    try:
        data = loads(urlopen('https://www.beeminder.com/api/v1/users/me/goals/%s.json?auth_token=%s&datapoints=true' % (goal,auth_token)).read().decode('utf-8'))
    except:
        print("Oops, there seems to be no goal named '%s'!" % (goal))
        exit(1)
    try:
        print(''.join(('::: Progress on %s :::\n\n%s\nBare minimum: %s\n' % (data['title'],data['headsum'],data['limsum']),'\n'.join(wrap(data['graphsum'])),'\n\n%s\n' % data['graph_url'])))
    except KeyError:
        print("Oops, there seems to be no goal named '%s'!" % (goal))
        exit(1)
    data = loads(urlopen('https://www.beeminder.com/api/v1/users/me/goals/%s/datapoints.json?auth_token=%s' % (goal,auth_token)).read().decode('utf-8'))
    for i in data[:10]:
        print(datetime.fromtimestamp(i['timestamp']).date(), i['value'], i['comment'])

# output for running "bmndr refresh <goal>"
elif len(argv) == 3 and argv[1] == "refresh":
    goal = argv[2]
    post = dict()
    if loads(urlopen('https://www.beeminder.com/api/v1/users/me/goals/%s/refresh_graph.json?auth_token=%s' % (goal, auth_token)).read().decode('utf-8')):
        print("Successfully refreshed %s goal" % goal)
    else:
        print("Failed to refresh %s goal" % goal)

# output for running "bmndr <goal> <data> <comment>"
else:
    goal = argv[1]
    
    post = dict()
    post['auth_token'] = auth_token
    post['timestamp'] = round(time())
    post['value'] = argv[2]
    if len(argv)>3:
        post['comment'] = ' '.join(argv[3:])
    else:
        post['comment'] = 'via bmndr at %s' % datetime.now().strftime('%X')

    params = urlencode(post)
    params = params.encode('utf-8')

    data = loads(urlopen('https://www.beeminder.com/api/v1/users/me/goals/%s/datapoints.json' % goal, params).read().decode('utf-8'))
    pprint(data)
