#!/usr/bin/env python

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3

from winswitch.net import pybonjour
from winswitch.util.simple_logger import Logger
from winswitch.net.net_util import get_iface, if_nametoindex
from twisted.internet.interfaces import IReadDescriptor
from zope import interface

logger = Logger("twisted_bonjour", Logger.YELLOW)

import sys
DEBUG = "--debug-mdns" in sys.argv

class ServiceDescriptor:
	"""
	Glue for integrating a pybonjour service with twisted.
	See: http://www.indelible.org/ink/twisted-bonjour/
	"""

	interface.implements(IReadDescriptor)

	def __init__(self, sdref):
		if DEBUG:
			logger.sdebug(None, sdref)
		self.sdref = sdref

	def doRead(self):
		if DEBUG:
			logger.sdebug(None)
		pybonjour.DNSServiceProcessResult(self.sdref)

	def fileno(self):
		fileno = self.sdref.fileno()
		if DEBUG:
			logger.sdebug("=%s" % fileno)
		return fileno

	def logPrefix(self):
		return "bonjour"

	def connectionLost(self, reason):
		logger.slog(None, reason)
		self.sdref.close()



def get_interface_index(host):
	if host == "0.0.0.0" or host =="" or host=="*":
		return	pybonjour.kDNSServiceInterfaceIndexAny
		#kDNSServiceInterfaceIndexLocalOnly

	if not if_nametoindex:
		logger.serror("cannot convert interface to index (if_nametoindex is missing), so returning 'IndexAny', pybonjour will publish on ALL interfaces", host)
		return	pybonjour.kDNSServiceInterfaceIndexAny


	iface = get_iface(host)
	if not iface:
		return	None

	return	if_nametoindex(iface)
