#!/usr/bin/env python
"""
CLI utility for logging the time you spend on things.
    Usage: `lt --help`
"""

import os
from datetime import date, timedelta

import click
from logtime_cli.logtime import log_time, open_logfile_for_date, continue_last_entry
from logtime_cli.logtime_config import open_user_config, get_option


def _open_previous(ctx, param, value):
    del param
    if not value:
        return
    previous_date = (date.today() - timedelta(days=value))
    try:
        open_logfile_for_date(previous_date)
    except WindowsError:
        print "No logfile exists for " + str(previous_date) + "."

    ctx.exit()


def _open_yesterday(ctx, param, value):
    if not value:
        return
    _open_previous(ctx, param, 1)


def _continue(ctx, param, value):
    del param
    if not value:
        return
    continue_last_entry()
    ctx.exit()


def _open_user_config(ctx, param, value):
    del param
    if not value:
        return
    open_user_config()
    ctx.exit()


def _open_logfile_directory(ctx, param, value):
    del param
    if not value:
        return
    log_file_directory = get_option('DEFAULT', 'logfile_directory')
    os.startfile(log_file_directory)
    ctx.exit()


@click.command(context_settings=dict(help_option_names=['-h', '--help']))
@click.option('--previous', '-p', type=int, callback=_open_previous, expose_value=False,
              is_eager=True, help='Open a logfile X days in the past and exit.')
@click.option('--yesterday', '-y', is_flag=True, callback=_open_yesterday, expose_value=False,
              is_eager=True, help='Open yesterdays logfile and exit. Alias for `-p 1`.')
@click.option('--continue', '-c', is_flag=True, callback=_continue, expose_value=False,
              is_eager=True,
              help='Continue the most recent entry by updating the end date and exit.')
@click.option('--config', is_flag=True, callback=_open_user_config, expose_value=False,
              is_eager=True, help='Open user config file and exit.')
@click.option('--dir', is_flag=True, callback=_open_logfile_directory, expose_value=False,
              is_eager=True, help='Open logfile directory and exit.')
@click.argument('entry', nargs=-1)
@click.option('--start', '-s',
              help='Choose a start time for this entry. Format: `0130p`, `01:30p, `1330`, `13:30`.')
@click.option('--end', '-e',
              help='Choose an end time for this entry. Format: `0130p`, `01:30p, `1330`, `13:30`.')
def cli(entry, start, end):
    """Log what you just finished doing.

    Examples:

    \b
    lt python docs
    lt john: discuss python docs

    \b
    To open today's logfile and exit, use:
    lt
    """
    if not entry:
        open_logfile_for_date(date.today(), can_create=True)
    else:
        log_time(' '.join(entry), start, end)

if __name__ == '__main__':
    cli() #pylint: disable=e1120
