#!/usr/bin/env python
"""Run Pomodoro

Usage:
    pomo [options] DURATION [DESCRIPTION ...]

Options:
    -c CONFIG --config=CONFIG    name of config file [default: ~/.pomorc]
    -l FILE --log-file=FILE      name of log file to write duration to
                                 [default: None]
    -s SOUND --sound-file=SOUND  name of sound file to play when a pomodoro is
                                 over [default: beep.mp3]
    -z SECONDS --snooze=SECONDS  duration of snoozing [default: 180]
"""
import os
from docopt import docopt
import yaml

from pomo import utils, core
from pomo import version

TIMES = {
    'test': 6,
    'work': 60*25,
    'short': 60*5,
    'long': 60*15,
    'snooze': 60*3,
}


def parse_config(args):
    config_file = os.path.expanduser(args['--config'])
    if os.path.exists(config_file):
        with open(config_file) as f:
            cfg = yaml.load(f.read())
    else:
        cfg = {}

    cfg.setdefault('times', TIMES)
    cfg['times'].setdefault('snooze', int(args['--snooze']))
    if not int(args['--snooze']) == 180:
        cfg['times']['snooze'] = int(args['--snooze'])

    if 'log_file' not in cfg and args['--log-file'] is not None:
        cfg['log_file'] = args['--log-file']
    if 'sound_file' not in cfg:
        cfg['sound_file'] = args['--sound-file']
    elif not args['--sound-file'] == 'beep.mp3':
        cfg['sound_file'] = args['--sound-file']

    if not os.path.exists(config_file) and args['--config'] == '~/.pomorc':
        with open(config_file, 'w') as f:
            f.write(yaml.dump(cfg))

    return cfg


def done():
    return False


ACTIONS = {'d': ('Done', done)}


if __name__ == '__main__':
    docopt = docopt(__doc__, version=version)
    cfg = parse_config(docopt)

    description = ' '.join(docopt['DESCRIPTION'])
    duration = cfg['times'][docopt['DURATION']]

    print('{}: {}'.format(docopt['DURATION'], description))
    dt = core.start_interval(duration,
                             ACTIONS,
                             os.path.expanduser(cfg['sound_file']),
                             snooze_duration=cfg['times']['snooze'])
    print('\rInterval:', dt)

    log_file = os.path.expanduser(cfg['log_file'])
    if log_file is not None:
        utils.write_info(log_file, dt, docopt['DURATION'], description)
