#!/usr/bin/python
import argparse
import logging
import os
import sys
import time
from daemons import daemonizer

from watchdog.observers import Observer

from monitor.controllers import EventsHandler, ConfigHandler
from monitor.services import UpdateQueue

help_info = "Monitor a folder and write events to SQS"

parser = argparse.ArgumentParser(description=help_info)

parser.add_argument("-q", "--queue_url",
                    help="Path to ACS. For example https://sqs.us-east-1.amazonaws.com/accountid/myqueue",
                    required=False)
parser.add_argument("-f", "--folder", help="path to folder to monitor, or comma separated list of paths",
                    required=False)

parser.add_argument("-c", "--config_file", help="Full path to config file", required=False)

args = parser.parse_args()

if not args.config_file and not (args.queue_url and args.folder):
    print("Either -c/--config_file is required or -q/--queue_url and -f/--folder are required")
    exit(1)


def main():
    config: ConfigHandler = ConfigHandler(args)

    update_queue: UpdateQueue = UpdateQueue(queue_url=config.queue_url)
    update_queue.test_queue()  # verify that we can send a message to the queue before continuing

    event_handler = EventsHandler(config.queue_url)
    observers = []

    for folder in config.folders:
        observer = Observer()
        observer.schedule(event_handler, folder, recursive=True)
        observer.start()
        observers.append(observer)

    try:
        while True:
            time.sleep(1)

    except KeyboardInterrupt:
        for observer in observers:
            observer.stop()
    for observer in observers:
        observer.join()


if __name__ == "__main__":
    myname = os.path.basename(sys.argv[0])
    pidfile = '/tmp/%s' % myname
    logging.info('Starting as daemon {name}'.format(name=myname))
    pid_path = "/tmp/{name}.pid".format(name=myname)


    @daemonizer.run(pidfile=pid_path)
    def run():
        print("PID File: " + pid_path)
        f = open(pid_path, "r")
        print("PID: " + f.read())
        main()


    run()
