#!/usr/bin/python
import zzz

class Notice(zzz.CNotice):
  def __init__(self, zclass, zinst, opcode, sender, recip, deffmt):
     self.zclass = zclass
     self.zinst = zinst
     self.opcode = opcode
     self.sender = sender
     self.recip = recip
     self.deffmt = deffmt
     zzz.CNotice.__init__(self, self.zclass, self.zinst, self.opcode, self.sender, self.recip, self.deffmt)
  def receive(self):
     zzz.CNotice.receive(self)
     self.zclass = self.znt.zclass
     self.zinst =  self.znt.zinst
     self.opcode = self.znt.opcode
     self.sender = self.znt.sender
     self.recip =  self.znt.recip
     self.deffmt = self.znt.deffmt

class Subscription(zzz.CSubscription):
   def __init__(self, zrecip, zclass, zinst):
      self.zrecip = zrecip
      self.zclass = zclass
      self.zinst = zinst
      zzz.CSubscription.__init__(self, zrecip, zclass, zinst)

class Subscriptions(list):
   def __iadd__(self, s):
      list.__iadd__(self, Subscription(*s))
   def sub(self, port):
      for s in self:
         s.sub(port)
   def unsub(self, port):
      for s in self:
         s.unsub(port)
   def cancel(self, port):
      self[0].cancel(port)


def printuser(user,host,when,tty):
    print "Z:","|".join([user,host,when,tty])

class AsyncLocation(zzz.CAsyncLocation):
   def __init__(self, users):
      if type(users) != type([]):
         users = [users]
      self.users = users
      self.cn = zzz.LocNotice("", "", "", "", "", "")
   def locate(self, hook=printuser):
      uset = {}
      for user in self.users:
         self.request(user)
         uset[user] = 1
      oneloc = zzz.CLocation()
      while uset:
         self.cn.zreceive()
         user = self.cn.parseloc()
         while 1:
             res = oneloc.getloc()
             if res:
                 hook(user, *res)
             else:
                 # print "nothing for",user # debugging; should this call hook?
                 del uset[user]
                 break
   def locations(self):
       results = {}
       for user in self.users:
           results[user] = []
       def hook(user,host,when,tty):
           results[user] += [[host,when,tty]]
       self.locate(hook=hook)
       return results

def zctl_ld(zf, port):
    for subline in file(zf):
        zclass, zinst, zrecip = subline.rstrip().split(",")
        # no -- the "*" -> "" handling is in the C library, not the apps
        #if zinst == "*": zinst = ""
        #if zrecip == "*": zrecip = ""
        if zrecip == "%me%": zrecip = zzz.sender() # athena(os.environ["USER"])
        #define	TOKEN_HOSTNAME	"%host%"  -- gethostname()
        #define	TOKEN_CANONNAME	"%canon%" -- gethostbyname(gethostname())
        #define	TOKEN_ME	"%me%"    -- ZGetSender
        #define	TOKEN_WILD	"*"
        # add zrecip.startswith("-") etc. here
        print (zrecip, zclass, zinst)
        othersub = Subscription(zrecip, zclass, zinst)
        othersub.sub(port)