from twisted.web import resource, static
import cgi, logging
from nevow import inevow, rend, tags, loaders, flat
import os, sys
from twisted.internet import reactor, defer

log = logging.getLogger("Webgui")
curdir=os.path.abspath(os.path.dirname(sys.argv[0]))
template_path = curdir+'/Web/html/Admin/'


class killUser(rend.Page):

   addSlash = True


   def __init__(self, user, command):
      self.command = command
      log.debug("Killing" + str(user))
      try:
         user['connection'].StopAndClose()
      except:
         log.debug("User not found")
         try:
            self.command('killUserData', user)
         except:
            pass
      rend.Page.__init__(self)


   def returnHTTP(self, ctx):
      request = inevow.IRequest(ctx)
      request.setHeader('Location', '/userlist')
      request.setResponseCode(302)
      html = '<html><head><title>SkyLive Daemon</title></head>'
      html = html+'</body></html>'
      return html


   def renderHTTP( self, ctx):
      d = defer.Deferred()
      d.addCallback(self.returnHTTP)
      reactor.callLater(2, d.callback, ctx)
      return d

   def childFactory(self, ctx, data):
      return self


class Page(rend.Page):
   
   addSlash=True

   def childFactory(self, ctx, data):
      ulist = self.command('UserList')
      if not data in ulist:
         return self.childPermissionDenied()
      else:
         user = self.command('getUserData', data)
         return killUser(user, self.command)
