import decra as DECRA
import logging

# 'dec': 23:44:43.1, 'ra': 5:48:58.68

log = logging.getLogger( 'EPHEM' )


class Ephem:

   def __init__(self, long, lat, obsName):
      self.lat, self.long = self.cleancord(lat, long)
      self.obsName = obsName
      self.utcDiff = 0
      self.dataSearch = DECRA.dataSet()

   def cleancord(self, lat, lon):
      nlat = lat.replace(" ", ":").replace(",", ":").replace("'","")
      nlat = nlat.replace("S","").replace("N","")
      if lat[-1:] == 'S': nlat = '-'+nlat
      nlon = lon.replace(" ", ":").replace(",", ":").replace("'","")
      nlon = nlon.replace("E","").replace("W","").replace("O", "")
      if lon[-1] == 'W': nlon = '-'+nlon
      if lon[-1] == 'O': nlon = '-'+nlon
      return nlat, nlon


   def setDecraVars(self):
      self.dataSearch.put_obsSite(self.long, self.lat, self.obsName)
      self.dataSearch.put_utcDiff(self.utcDiff)
      self.dataSearch.getLandPos()

   def getDECRAbyCMD(self, objs=False):
      ret=False
      if objs:
         obje = objs.upper().replace(' ','')
         if 'CNGC' in obje:
            ret = self.dataSearch.getDECRA(obje.replace('CNGC','NGC'))
         elif 'MESSIER' in obje:
            ret = self.dataSearch.getDECRA(obje.replace('MESSIER',''))
         elif 'PIANETA' in obje:
            log.debug("Pianeta richiesto: "+str(obje))
            ret = self.dataSearch.managePlanetCMD(obje)
         else:
            ret = False
            if len(obje) > 2:
               if 'IC' in obje[:2]:
                  ret = self.dataSearch.getDECRA(obje.replace('IC', ''))
            if not ret:
               ret = self.dataSearch.getDECRA()
      log.debug("Ephem return: "+str(ret))
      return ret


   def queryDecra(self, cmd):
      log.debug("queryDecra for command "+str(cmd))
      self.setDecraVars()
      res = self.getDECRAbyCMD(cmd)
      try:
         ret=False
         log.debug("EPHEM RESPONSE: "+str(res))
         if res['result'] == 'ok' and  res['hl'] == 'ok':
            ret = self.getLx200Command(cmd, res['ra'], res['dec'])
            log.debug("Returning coordinates: "+str(ret))
         return ret
      except:
         log.debug("queryDecra Exception")
         return False


   def getLx200Command(self, obj, ra, dec):
      try:
         signra=""
         rah=str(ra).split(":")[0].zfill(2)
         if rah[:1] in ['+', '-']: 
            signra=rah[:1]
            rah=rah[1:].zfill(2)
         if int(rah) > 23:
            return False
         ram=str(ra).split(":")[1].zfill(2)
         if int(ram) > 59:
            return False
         ras=str(int(int(str(ra).split(":")[2].split(".")[0])*10)/60).zfill(1)
         #ras=str(int(int(str(ra).split(":")[2][0].zfill(1))*10)/60).zfill(1)
         if int(ras) > 9:
            return False
         ra=signra+rah+":"+ram+"."+ras

         signdec=""
         dec1=str(dec).split(":")[0].zfill(2)
         if dec1[:1] in ['+', '-']: 
            signdec=dec1[:1]
            dec1=dec1[1:].zfill(2)
         if int(dec1) > 89:
            return False
         dec2=str(dec).split(":")[1]
         if int(dec2) > 99:
            return False
         dec = signdec+dec1+'.'+dec2
         if dec[:1] not in ['+', '-']:
            dec = '+'+dec
         return [str(ra), str(dec)]
      except:
         return False

   def getALTAZbyRADEC(self, ra=False, dec=False):
      if ra and dec:
         self.setDecraVars()
         ret = self.dataSearch.getAltAzbyRaDec(ra, dec)
      else:
         ret = False
      return ret

