import sys
import os
import paho.mqtt.client as mqttClient
import time
from datetime import date
import json

# Paho MQTT Setup
Connected = False
broker_address = "192.168.200.55"
port = 1883
user = "hass"
password = "Over9+look*"
client = mqttClient.Client("Python")

# Working Dir setup
# rootdir = "/Users/normrasmussen/Documents/Work/CustomerNotes/"
# todoDir = "/Users/normrasmussen/Documents/Work/"
rootdir = "/Users/normrasmussen/Documents/Work/Scripts/Todo_reorg/"
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 "TODO:" in fullTasks:
                tasks = fullTasks
                create_payload(tasks)
                # deleteTasks(rootdir, company, tasks)
                todos.append(tasks)
    # writeTasks(company, todos)
    # create_payload(todos)


def create_payload(tasks):
    payload = {}
    client.username_pw_set(user, password=password)
    client.on_connect = on_connect
    client.connect(broker_address, port=port)
    client.loop_start()
    # for todo in todos:
    time.sleep(5)
    status = tasks.split()[0]
    status = status[:-1]

    todo = tasks[6:-1]
    payload = {"status": status, "task": todo}
    payload = str(payload)
    print(payload)
    client.publish("home/todos", payload)

    # Wait for a connection - This was used by the tutorial
# Tutorial:
# https://techtutorialsx.com/2017/04/14/python-publishing-messages-to-mqtt-topic/
    # while Connected != True:
    #     time.sleep(0.1)
    # try:
    #     while True:
    #         client.publish("home/todos", payload)
    # except KeyboardInterrupt:
    #     client.disconnect()
    #     client.loop_stop()


def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to broker")

        global Connected
        Connected = True

    else:
        print("Connection failed")


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