#!/usr/bin/env python

import click
import os
from datetime import date, timedelta
from logtime_cli.logtime import LogTime, OpenLogfileForDate
from logtime_cli.logtime_config import OpenUserConfig, GetOption


def _openPrevious(ctx, param, value):
    if not value:
        return
    previousDate = (date.today() - timedelta(days=value))
    try:
        OpenLogfileForDate(previousDate)
    except WindowsError as e:
        print "No logfile exists for " + str(previousDate) + "."

    ctx.exit()


def _openYesterday(ctx, param, value):
    if not value:
        return
    _openPrevious(ctx, param, 1)


def _openUserConfig(ctx, param, value):
    if not value:
        return
    OpenUserConfig()
    ctx.exit()


def _openLogfileDirectory(ctx, param, value):
    if not value:
        return
    logFileDirectory = GetOption('DEFAULT', 'logfile_directory')
    os.startfile(logFileDirectory)
    ctx.exit()


@click.command(context_settings=dict(help_option_names=['-h', '--help']))
@click.option('--previous', '-p', type=int, callback=_openPrevious, 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=_openYesterday, expose_value=False, is_eager=True, help='Open yesterdays logfile and exit. Alias for `-p 1`.')
@click.option('--config', is_flag=True, callback=_openUserConfig, expose_value=False, is_eager=True, help='Open user config file and exit.')
@click.option('--dir', is_flag=True, callback=_openLogfileDirectory, 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:
        OpenLogfileForDate(date.today(), canCreate=True)
    else:
        LogTime(' '.join(entry), start, end)

if __name__ == '__main__':
    cli()
