#!/usr/bin/env python

import zmq
import argparse
import os
import pipes
import re
import sys

# get command line argument (hostname)
parser = argparse.ArgumentParser(description='Connect to notification queue')
parser.add_argument('hostname', nargs=1, help='Where Weechat is running')
args = parser.parse_args()
hostname = args.hostname[0]

# start socket connection
context = zmq.Context()
socket = context.socket(zmq.SUB)
try:
    socket.connect("tcp://%s:5000" % hostname)
except:
    print "Cannot make connection to %s." % hostname
    sys.exit(1)

# subscribe to `message` queue
socket.setsockopt(zmq.SUBSCRIBE, "message")

# detect os/notification system
if os.system("type terminal-notifier >/dev/null 2>&1") == 0:
    ismac = True
    openingbrackets = re.compile(r'^([\[\{\<\(])')
    notifiercommand = "terminal-notifier -title 'IRC' " \
                      "-subtitle {0} -message {1}"
elif os.system("type notify-send >/dev/null 2>&1") == 0:
    ismac = False
    notifiercommand = "notify-send --icon=notification-message-im {0} {1}"
else:
    print "Cannot find terminal-notifier or notify-send," \
          "so running this will do nothing. Quitting instead."
    sys.exit(1)

os.system(
    notifiercommand.format(
        "weechat-zmq-notifier",
        pipes.quote("Successfully started. Now listening for messages.")
    )
)

while True:
    try:
        queue, data = socket.recv().split(" ", 1)
        name, message = data.split("\t", 1)

        # fix opening brackets for terminal-notifier on OS X
        if ismac:
            name = openingbrackets.sub(r'\\\1', name)
            message = openingbrackets.sub(r'\\\1', message)

        os.system(
            notifiercommand.format(
                pipes.quote(name),
                pipes.quote(message)
            )
        )

    except (KeyboardInterrupt, SystemExit):
        sys.exit('Quitting...')
