from twisted.web import client
from twisted.internet import defer, reactor, task
import logging
from BeautifulSoup import BeautifulSoup

log = logging.getLogger("Observatory")


class wheather:

   status = 'Unknown'
   oldstatus = 'Unknown'

   def __init__(self):
      log.debug("Starting Looping to set GCO Wheather status")
      self.ccall = task.LoopingCall(self.getStatus)

   def startCron(self, timeout=600):
      try:
         self.ccall.stop()
      except:
         pass
      self.ccall.start(timeout)

   def stopCron(self):
      log.debug("Calling stopCron for GCO wheather")
      try:
         self.ccall.stop()
      except:
         pass
      self.status = 'Unknown'
      self.oldstatus = 'Unknown'
      try:
         self.command('WStatus', 'gco')
      except:
         pass

   def getStatus(self):
      #return client.getPage("http://remote.gco.org.au/sao/gcocloud.html").addCallback(self.setStatus
		return client.getPage("http://www.gco.org.au/weather/weather2.html").addCallback(self.setStatus
            ).addErrback(lambda _: log.debug("Error setting status for GCO weather"))

   def setStatus(self, res):
      if res:
         try:
            html = BeautifulSoup(res)
            intstat = int(str(html.findChild('body')).replace("<body>",
               "").replace("\r","").replace("\n", "").replace("status",
               "").replace("=", "").replace("</body>",
               "").replace(" ","").replace("'", ""))

            log.debug("GCO STATUS RECEIVED: "+str(intstat))
            #strstat = str(html.findAll('body')[0]).replace("<body>", "").replace("</body>","")
            #self.status = strstat.replace("START", "").replace("STOP", "").replace("END", "")
            #star = {1: 'Clear',
            #        2: 'Cloudy',
            #        3: 'Overcast',
            #        4: 'Raining'}
            star = {1: 'Clear',
                    2: 'Cloudy',
                    3: 'Vcloudy',
                    4: 'Rain'}
            self.status = star[intstat]
         except:
            log.debug("Error: cannot set GCO status,  why?")
            self.status = 'Unknown'
      else:
         self.status = 'Unknown'
      try:
         if self.oldstatus != self.status:
            log.warning("Setting wheather status "+self.status+" for GCO")
            self.oldstatus = self.status
            self.command('WStatus', 'gco')
      except:
         pass

      return defer.succeed(True)

class dome:

   status = 'Unknown'
   oldstatus = 'Unknown'

   def __init__(self):
      log.debug("Starting Looping to set GCO Dome status")
      self.ccall = task.LoopingCall(self.getStatus)

   def startCron(self, timeout=5):
      try:
         self.ccall.stop()
      except:
         pass
      self.ccall.start(timeout)

   def stopCron(self):
      log.debug("Calling stopCron for GCO dome")
      try:
         self.ccall.stop()
      except:
         pass
      self.status = 'Unknown'
      self.oldstatus = 'Unknown'
      try:
         self.command('DStatus', 'gco')
      except:
         pass


   def getStatus(self):
      return self.setStatus(self.command('getRoof', ['6']))


   def setStatus(self, res):
      log.debug("GCO setStatus roof "+str(res))
      self.status=res
      if str(res) not in ['Open', 'Closed']:
         self.status='Unknown'
      try:
         if self.oldstatus != self.status:
            log.warning("Setting dome status "+self.status+" for GCO")
            self.oldstatus = self.status
            self.command('DStatus', 'gco')
      except:
         pass
      
      return defer.succeed(True)


   """
   def getStatus(self):
      return client.getPage("http://remote.gco.org.au/sao/gcostat.asp").addCallback(self.setStatus
            ).addErrback(lambda _: log.debug("Error setting status for GCO dome"))

   def setStatus(self, res):
      if res:
         try:
            html = BeautifulSoup(res)
            strstat = str(html.findAll('tr')[1].findAll('td')[1])
            if strstat == '<td>*** ROOF HAS BEEN ARMED ***</td>':
               self.status = 'Open'
            else:
               self.status = 'Closed'
         except:
            self.status = 'Unknown'
      else:
         self.status = 'Unknown'
      try:
         if self.oldstatus != self.status:
            log.warning("Setting dome status "+self.status+" for GCO")
            self.oldstatus = self.status
            self.command('DStatus', 'gco')
      except:
         pass

      return defer.succeed(True)
   """

