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


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

#lowliveguide = http://skylive.astronomix.org/tele6/
#highliveguide = http://skylive.astronomix.org.nyud.net/tele6/
#lowhightlimit = 10
#lowliveguideint = 5
#highliveguideint = 5
#getSet ... Options

class TelContent(rend.Page):

   addSlash=True
   docFactory = loaders.xmlfile('telescopi_tel.html', templateDir=template_path)

   def renderHTTP(self, ctx):
      log.debug("Called renderHTTP")
      request = inevow.IRequest(ctx)
      if request.method == 'POST':
         log.debug("POST TelContent")
         try:
            if request.args["Aggiorna"][0] == 'Aggiorna':
               log.debug("Aggiornamento config")
               for key in request.args.keys():
                  if key in ['useforcestatus',
                             'whitelist',
                             'reserved',
                             'forcestatus',
                             'onlinestatus',
                             'offlinestatus',
                             'model',
                             'focal',
                             'fov',
                             'observatory',
                             'ccd',
                             'filters',
                             'useautoephem',
                             'meridianprotection',
                             'bin',
                             'lowliveguide',
                             'highliveguide',
                             'lowhightlimit',
                             'lowliveguideint',
                             'highliveguideint',
                             'silenced',
                             'enablestreaming',
                             'streaminguri',
                             'setccdtemp']:
                     if key == 'bin': 
                        bin = request.args[key][0]
                     else:
                        self.cfg.set(self.tname, key, request.args[key][0])
                     if key == 'setccdtemp':
                        if not (int(request.args[key][0]) <= 40 and int(request.args[key][0]) >= -40):
                           request.args[key][0] = '0'
                        else:
                           request.args[key][0] = str(int(request.args[key][0]))
                     if key == 'lowhightlimit':
                        if not int(request.args[key][0]) >= 3:
                           request.args[key][0] = '3'
                        else:
                           request.args[key][0] = str(int(request.args[key][0]))
                     if key in ['lowliveguideint', 'highliveguideint']:
                        if not int(request.args[key][0]) >= 5:
                           request.args[key][0] = '5'
                        else:
                           request.args[key][0] = str(int(request.args[key][0]))


               if len(bin) > 0 and str(bin).replace(",", "").replace(" ", "").isdigit() :
                  self.cfg.set(self.tname, 'bin', bin.replace(" ",""))
               else:
                  self.cfg.set(self.tname, 'bin', "1,2,3")

               try:
                  self.cfg.writeConfig()
                  self.command('ReloadTelConfig')
               except:
                  pass
         except:
            pass
      return rend.Page.renderHTTP(self, ctx)

   def render_getTelescopeName(self, ctx, data):
      return self.tname

   def render_getFormAction(self,ctx, data):
      return '/telescopi/'+self.cname

   def render_getOnlineStatus(self, ctx, data):
      return self.cfg.get(self.tname, 'onlinestatus')

   def render_getOfflineStatus(self, ctx, data):
      return self.cfg.get(self.tname, 'offlinestatus')

   def render_getForcedStatus(self, ctx, data):
      return self.cfg.get(self.tname, 'forcestatus')

   def render_getUseForcedOptions(self, ctx, data):
      option = self.cfg.get(self.tname, 'useforcestatus')
      if option.lower() == 'yes' or option.lower() == 'true':
         return loaders.stan(tags.select(name="useforcestatus")[
                                 tags.option(value="yes", selected="selected")["yes"],
                                 tags.option(value="no")["no"]
                                 ])
      return loaders.stan(tags.select(name="useforcestatus")[
                           tags.option(value="yes")["yes"],
                           tags.option(value="no", selected="selected")["no"]
                           ])


   def render_getenablestreaming(self, ctx, data):
      option = self.cfg.get(self.tname, 'enablestreaming')
      if option.lower() == 'yes' or option.lower() == 'true':
         return loaders.stan(tags.select(name="enablestreaming")[
                                 tags.option(value="yes", selected="selected")["yes"],
                                 tags.option(value="no")["no"],
                                 tags.option(value='force')['force'],
                                 ])
      elif option.lower() == 'force':
         return loaders.stan(tags.select(name="enablestreaming")[
                                 tags.option(value="yes")["yes"],
                                 tags.option(value="no")["no"],
                                 tags.option(value='force', selected="selected")["force"],
                                 ])
      return loaders.stan(tags.select(name="enablestreaming")[
                           tags.option(value="yes")["yes"],
                           tags.option(value="no", selected="selected")["no"],
                           tags.option(value='force')['force']
                           ])


   def render_getWhiteList(self, ctx, data):
      return self.cfg.get(self.tname, 'whitelist')

   def render_getReservedList(self, ctx, data):
      return self.cfg.get(self.tname, 'reserved')

   def render_getModel(self, ctx, data):
      return self.cfg.get(self.tname, 'model')

   def render_getFocal(self, ctx, data):
      return self.cfg.get(self.tname, 'focal')

   def render_getFov(self, ctx, data):
      return self.cfg.get(self.tname, 'fov')

   def render_getCcd(self, ctx, data):
      return self.cfg.get(self.tname, 'ccd')

   def render_getlowliveguide(self, ctx, data):
      return self.cfg.get(self.tname, 'lowliveguide')

   def render_getlowliveguideint(self, ctx, data):
      return self.cfg.get(self.tname, 'lowliveguideint')

   def render_gethighliveguide(self, ctx, data):
      return self.cfg.get(self.tname, 'highliveguide')

   def render_gethighliveguideint(self, ctx, data):
      return self.cfg.get(self.tname, 'highliveguideint')

   def render_getlowhightlimit(self, ctx, data):
      return self.cfg.get(self.tname, 'lowhightlimit')


   def render_getstreaminguri(self, ctx, data):
      return self.cfg.get(self.tname, 'streaminguri')


   def render_getSetCcdTempOptions(self, ctx, data):
      option = self.cfg.get(self.tname, 'setccdtemp')
      rangetemps = range(-40, 41)
      L = []
      for t in rangetemps:
         if str(t) == str(option):
            L.append(tags.option(value=str(t), selected="selected")[str(t)])
         else:
            L.append(tags.option(value=str(t))[str(t)])
      return loaders.stan(tags.select(name="setccdtemp")[L])

   def render_getObservatory(self, ctx, data):
      option = self.cfg.get(self.tname, 'observatory')
      observatoryes = ['Unknown']
      log.debug(self.obscfg.sections())
      for observ in self.obscfg.sections():
         observatoryes.append(observ)
      htmlopt = []
      for obs in observatoryes:
         if option == obs:
            htmlopt.append(tags.option(value=obs, selected='selected')[obs])
         else:
            htmlopt.append(tags.option(value=obs)[obs])
      html = tags.select(name='observatory')[htmlopt]
      return loaders.stan(html)

   def render_getFilters(self, ctx, data):
      return self.cfg.get(self.tname, 'filters')

   def render_getBin(self, ctx, data):
      return self.cfg.get(self.tname, 'bin')

   def render_getAutoEphemOptions(self, ctx, data):
      option = self.cfg.get(self.tname, 'useautoephem')
      if option.lower() == 'yes' or option.lower() == 'true':
         return loaders.stan(tags.select(name="useautoephem")[
                                 tags.option(value="yes", selected="selected")["yes"],
                                 tags.option(value="no")["no"]
                                 ])
      return loaders.stan(tags.select(name="useautoephem")[
                           tags.option(value="yes")["yes"],
                           tags.option(value="no", selected="selected")["no"]
                           ])


   def render_getSetSilencedTempOptions(self, ctx, data):
      option = self.cfg.get(self.tname, 'silenced')
      if option.lower() == 'yes' or option.lower() == 'true':
         return loaders.stan(tags.select(name="silenced")[
                                 tags.option(value="yes", selected="selected")["yes"],
                                 tags.option(value="no")["no"]
                                 ])
      return loaders.stan(tags.select(name="silenced")[
                           tags.option(value="yes")["yes"],
                           tags.option(value="no", selected="selected")["no"]
                           ])


   def render_getMeridianProtectionOptions(self, ctx, data):
      option = self.cfg.get(self.tname, 'meridianprotection')
      if option.lower() == 'yes' or option.lower() == 'true':
         return loaders.stan(tags.select(name="meridianprotection")[
                                 tags.option(value="yes", selected="selected")["yes"],
                                 tags.option(value="no")["no"]
                                 ])
      return loaders.stan(tags.select(name="meridianprotection")[
                           tags.option(value="yes")["yes"],
                           tags.option(value="no", selected="selected")["no"]
                           ])



class Page(rend.Page):
   
   addSlash=True
   docFactory = loaders.xmlfile('telescopi.html', templateDir=template_path)

   def __init__(self, avatarId=None):
      self.avatarId = avatarId
      log.debug("Requested Userlist by "+str(avatarId))
      rend.Page.__init__(self)

   def order_tlist(self, tlist):
      res = {}
      for i in tlist.keys():
         res[tlist[i]['name']] = tlist[i]
         res[tlist[i]['name']]['index'] = i
      return res

   def setPersistant(self, name, value):
      # We can get persistant variables here, 
      # so, setting this in the parent shuld work
      if not 'telescope' in self.parent.childvars.keys():
         self.parent.childvars['telescope'] = {}
      self.parent.childvars['telescope'][name] = value

   def getPersistant(self, name):
      if 'telescope' in self.parent.childvars.keys():
         if name in self.parent.childvars['telescope'].keys():
            return self.parent.childvars['telescope'][name]
      return False

   def render_TelescopeList(self, ctx, data):
      self.tlist = self.order_tlist(self.command('GetTelescopes'))
      self.setPersistant('tlist', self.tlist)
      html = '<div id="menubar"><ul>'
      keys = self.tlist.keys()
      self.setPersistant('ikeys', keys)
      keys.sort()
      ikeys = []
      for i in keys:
         ikeys.append(self.tlist[i]['index'])
         html = html+'<li><a href="/telescopi/tel'+self.tlist[i]['index']+'">'+self.tlist[i]['name']+'</a></li>'
      html = html+"</ul></div>"
      self.setPersistant('ikeys', ikeys)
      return ctx.tag[loaders.xmlstr(html)]

   def childFactory(self, ctx, data):
      print data
      if data[:3] == 'tel':
         tnum = data[3:]
         if self.getPersistant('ikeys') and tnum in self.getPersistant('ikeys'):
            tcon = TelContent()
            tcon.childFactory = self.childFactory
            tcon.render_HEAD = self.render_HEAD
            tcon.render_HEADER = self.render_HEADER
            tcon.render_FOOTER = self.render_FOOTER
            tcon.command = self.command
            tcon.order_tlist = self.order_tlist
            tcon.render_TelescopeList = self.render_TelescopeList
            tcon.cfg = self.command('GetTelescopeConfig')
            tcon.obscfg = self.command('GetObservatoryesConfig')
            tcon.tname = self.command('GetTelescopes')[tnum]['name']
            tcon.cname = data
            return tcon
      return self.childPermissionDenied()
