import sys
import os
import fileinput
from datetime import date

# rootdir = "/Users/normrasmussen/Documents/Northpass/CustomerNotes/"
# This is for testing
rootdir = "/Users/normrasmussen/Documents/Northpass/CustomerNotes/"
todoDir = "/Users/normrasmussen/Documents/Northpass/"
input = sys.argv[1]
company = input.split("/")[6]
print(company)


def findCompany(rootdir, company):
    files = os.listdir(rootdir)
    for fileName in files:
        if fileName.startswith(".") or fileName.startswith("Todos"):
            pass
        else:
            company = fileName[:-3]
            findTodos(rootdir, company)


def findTodos(rootdir, company):
    todos = []
    with open(rootdir + company, "r") as currentfile:
        file = currentfile.readlines()
        for fullTasks in file:
            if "* [ ] " in fullTasks:
                tasks = fullTasks
                deleteTasks(rootdir, company, tasks)
                todos.append(tasks)
    writeTasks(company, todos)


def writeTasks(company, todos):
    today = date.today()
    currentDate = today.strftime("%m/%d/%Y")
    company = company[:-3]
    todoDir = "/Users/normrasmussen/Documents/Northpass/"
    with open(todoDir + "Todos.md", "a") as taskFile:
        for singleTask in todos:
            task = singleTask.rsplit("* [ ] ")[1]
            taskFile.write(
                "* [ ] (" + company + ") " + "[" + currentDate + "]  " + task
            )


# def deleteCompleted(todoDir):
#    todoList = todoDir + "Todos.md"
#    with open(todoList, "r") as file_input:
#        with open(todoList, "w") as output:
#            for line in file_input:
#                if line.strip("\n") == "* [X] ":
#                    output.write(line)
# for line in fileinput.input(todoList, inplace=True):
# if line.strip().startswith("* [X] "):
# line = ''
# sys.stdout.write(line)
# TODO: Neither function deletes single lines, it seems to delete all lines. Fix this.

# def deleteCompleted(todoDir):
#    todoList = todoDir + "Todos.md"
#    with open(todoList, "r+") as file:
#        for line in file:
#            if line.startswith("* [X] "):
#                print(line)


def deleteTasks(rootdir, company, tasks):
    file = rootdir + company
    for line in fileinput.input(file, inplace=True):
        if tasks in line:
            line = line.replace(tasks, "")


#        sys.stdout.write(line)

if __name__ == "__main__":
    findTodos(rootdir, company)
    # deleteCompleted(todoDir)
