#!/usr/bin/python
#
# # wunderissues.py
# # MIT LICENSE
# # code by coolharsh55
# #
# # sync Github issues into Wunderlist lists

import json
from os import getenv

import github
import wunderlist

# load issues from github
issues = json.loads(
    github.get_issues(
        getenv('GITHUB_USERNAME'),
        getenv('GITHUB_ACCESS_TOKEN')))

# get repo names from issues -> issue dict.keys
github_repos = issues.keys()

# authenticate wunderlist
wunderlist.authenticate(
    client_id=getenv('WUNDERLIST_CLIENT_ID'),
    access_token=getenv('WUNDERLIST_ACCESS_TOKEN')
)

# get wunderlist lists
lists = wunderlist.get_lists()
wunderlist_lists = [f['title'] for f in lists]

# calculate which of the github repos are present as lists
have = [x for x in github_repos if x in wunderlist_lists]
have_nots = [x for x in github_repos if x not in have]
# create new lists from github repos not in wunderlist
for new_list in have_nots:
    response = wunderlist.create_list(new_list)

# get all lists including newly created lists
lists = wunderlist.get_lists()

# get list as list_ids
repo_lists = [l['id'] for l in lists if l['title'] in github_repos]

# get all folders
folders = wunderlist.get_folders()
# check if Github folder exists
if 'Github' not in [f['title'] for f in folders]:
    # Github does not exist, so let us create it
    wunderlist.create_folder('Github', repo_lists)
else:
    # retrieve existing Github folder
    github_folder = [f for f in folders if f['title'] == 'Github']


# sync github issues with tasks in wunderlist
for list_id in repo_lists:
    # retrieve all tasks for given list
    tasks = wunderlist.get_tasks(list_id)
    # get repo name
    repo_name = next(l['title'] for l in lists if l['id'] == list_id)
    # get github issues for this repo
    this_issues = issues[repo_name]

    # check if task exists in wunderlist
    for issue_number, issue_data in this_issues.items():
        # issue title = task title
        issue_title = issue_data['title']
        # issue info is the issue info inserted in task title
        issue_info = 'issue:{}'.format(issue_number)

        # check if issue is already present in list
        for task in [t['title'] for t in tasks]:
            # if issue info is in task title
            if issue_number in task:
                # issue number is present
                if issue_title not in task:
                    # issue title not present
                    # TODO: update task with issue title from github
                    pass
                else:
                    # issue number and title present
                    issue_info = None

        # should I insert the issue?
        if issue_info is not None:
            # add task to the list
            response = wunderlist.create_task(
                list_id,
                '#{0} {1} {2}'.format(
                    repo_name, issue_title, issue_info))
