#!/usr/bin/env python
# -*- mode: python -*-

"""This script uses the Trello configuration in trello.json and the Todoist
configuration in todoist.json to put Trello cards that are due today as todoist
tasks.
"""

import os
import json
import argparse
import datetime

from trello import TrelloClient
from todoist import TodoistAPI


def date_type(s):
    return datetime.datetime.strptime(s, '%Y-%m-%d').date()

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
    'trello_board_name',
    help='name of the Trello Board that we are parsing'
)
parser.add_argument(
    'trello_username',
    help='username of the person whose cards we want to populate'
)
parser.add_argument(
    'todoist_project_name',
    help='name of the todoist project to which due cards should be assigned'
)
parser.add_argument(
    '--trello-due-date',
    type=date_type,
    default=datetime.date.today(),
    help='due date of trello card in YYYY-MM-DD format (%(default)s)',
)
parser.add_argument(
    '--trello',
    type=argparse.FileType('r'),
    metavar='JSONFILE',
    default='trello.json',
    help='trello credentials file in json format',
)
parser.add_argument(
    '--todoist',
    type=argparse.FileType('r'),
    metavar='JSONFILE',
    default='todoist.json',
    help='todoist credentials file in json format',
)
args = parser.parse_args()


def is_due(card):
    """determine if a trello card is due or not"""
    return card.due_date and card.due_date.date() == args.trello_due_date


# get credentials and instantiate the client
credentials = json.load(args.trello)
client = TrelloClient(**credentials)

# find the appropriate board
board = None
for _board in client.list_boards():
    if _board.name == args.trello_board_name:
        board = _board
        break
if board is None:
    raise ValueError('board "%(trello_board_name)s" not found' % vars(args))

# find the appropriate member
member = None
for _member in board.get_members():
    if _member.username == args.trello_username:
        member = _member
        break
if member is None:
    raise ValueError('member "%(trello_username)s" not found' % vars(args))

# find all of the cards on this board that are owned by this user and are due
# today
cards_due_today = []
for card in board.all_cards():
    if member.id in card.member_ids and is_due(card):
        cards_due_today.append(card)

# create an authenticated instance of the TodoistAPI
credentials = json.load(args.todoist)
todoist_api = TodoistAPI(**credentials)

# get the project id
todoist_api.projects.sync()
project_id = None
for project in todoist_api.projects.all():
    if project['name'] == args.todoist_project_name:
        project_id = project['id']
if project_id is None:
    raise ValueError((
        'did not find todoists project "%(todoist_project_name)s"'
    ) % vars(args))

# add due cards as todoist tasks
for card in cards_due_today:
    todoist_api.add_item(
        '[%(name)s](%(url)s)' % vars(card),
        project_id=project_id,
        day_order=0,
        date_string='today',
    )
