#!/usr/bin/python

from pybrate import Dryer
from pyfttt import sending
from time import sleep
import os, sys

import argparse

def write_pid(pidfile):
    pid = str(os.getpid())
    if os.path.isfile(pidfile):
        print "%s already exists, exiting" % pidfile
        sys.exit()
    file(pidfile, 'w').write(pid)

def main():
    parser = argparse.ArgumentParser(description='Send dryer notifications')
    parser.add_argument('--key', '-k', default=False, required=True,
            help="IFTTT API key")
    parser.add_argument('--pid', '-p', default="/run/dryer.pid",
            help="Pid file location")
    args = parser.parse_args()
    apikey = args.key

    myDryer = Dryer()

    write_pid(args.pid)

    try:
        while myDryer.update():
            if myDryer.changed:
                if myDryer.running:
                    sending.send_event(apikey, "dryer_started")
                else:
                    sending.send_event(apikey, "dryer_finished")
            sleep(5)

    finally:
        os.unlink(args.pid)


if __name__ == '__main__':
    main()
