#!/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))
    OpenLogfileForDate(previousDate)
    ctx.exit()


def _openYesterday(ctx, param, value):
    if not value:
        return
    previousDate = (date.today() - timedelta(days=1))
    OpenLogfileForDate(previousDate)
    ctx.exit()


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)
def cli(entry):
    """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())
    else:
        LogTime(' '.join(entry))

if __name__ == '__main__':
    cli()
