import logging
import time

log = logging.getLogger('Clients')

deffrom="Server Skylive"
linestart=chr(221)
linestop=chr(222)
sep="#^#"


class clientParser:

   def __init__(self):
      pass

   def parseMsg(self, msg, *args, **kwargs):
      log.debug("Parse: "+msg)
      act = {}
      cmd = msg.split(sep)[2]
      f = getattr(self, 'on_'+cmd, None)
      if f and callable(f):
         act = f(msg)
         # XXX
         return act
      return False


   def on_CambioTele(self, msg):
      tnum = msg.split(sep)[3]
      return {'changeTelescope': tnum}


   def on_MSGTOALL(self, msg):
      return {'MsgToAll': msg.split(sep)[3]}

   def on_MSGPRIVATO(self, msg):
      mesg = msg.split(sep)[3]
      to = msg.split(sep)[4]
      if to[:1] == '@' or to[:1] == '!' or to[:1] == '>':
         to = to[1:]
      return {'PrivMsg': [to, mesg]}

   def on_COMANDO(self, msg):
      cmdr = msg.split(sep)[3]
      if cmdr in ['NORD', 'SUD', 'EST', 'WEST', 'OVEST']:
         if cmdr == 'WEST':
            cmdr = 'OVEST'
         return {'MoveCARDINAL': cmdr}
      elif cmdr[:4] == 'FOTO':
         cmd='FOTO'
      elif cmdr[:5] == 'MUOVI':
         cmd='MUOVI'
      elif cmdr[:4] == 'CNGC':
         cmd='CNGC'
      elif cmdr[:6] == 'CENTRA':
         cmd='CENTRA'
      elif cmdr[:2] == 'IC':
         cmd='IC'
      elif cmdr[:7] == 'Pianeta':
         cmd='PIANETA'
      elif cmdr[:7] == 'messier':
         cmd='MESSIER'
      else:
         cmd = 'UNKNOWN'
      f = getattr(self, 'on_COMANDO_'+cmd, None)
      if f and callable(f):
         return f(msg)


   def on_COMANDO_FOTO(self, msg):
      log.info("Foto: "+msg.split(sep)[3])
      # FOTO002C11001
      exp = msg.split(sep)[3][4:][:3]
      codestr = msg.split(sep)[3][7:]
      return {'MakePhoto': [exp, codestr]}

   def on_COMANDO_MUOVI(self, msg):
      log.info("Muovi: "+msg.split(sep)[3])
      # MUOVI00:00.0+00:00
      ar = msg.split(sep)[3][5:][:7]
      dec = msg.split(sep)[3][12:]
      return {'MoveARDEC': [ar, dec]}

   def on_COMANDO_CNGC(self, msg):
      log.info("Cngc: "+msg.split(sep)[3])
      cngc = msg.split(sep)[3]
      return {'MoveCngc': [cngc, msg.split(sep)[3]]}

   def on_COMANDO_CENTRA(self, msg):
      log.info("Centra: "+msg.split(sep)[3])
      centra = msg.split(sep)[4]
      return {'Center': centra}

   def on_COMANDO_IC(self, msg):
      log.info("Ic: "+msg.split(sep)[3])
      log.warning("IC objects aren't yet implemented!")

   def on_COMANDO_PIANETA(self, msg):
      log.info("Pianeta: "+msg.split(sep)[3])
      code = msg.split(sep)[3][7:][:4]
      descr = msg.split(sep)[3][11:]
      return {'MovePlanets': [code, descr, msg.split(sep)[3]]}

   def on_COMANDO_MESSIER(self, msg):
      log.info("Messier: "+msg.split(sep)[3][7:])
      mes = msg.split(sep)[3][7:]
      return {'MoveMessier': [mes, msg.split(sep)[3]]}

   def on_ADMINACTION(self, msg):
      f = getattr(self, 'on_ADMINACTION_'+cmd, None)
      if f and callable(f):
         return f(msg)

   def on_ADMINACTION_STOP(self, msg):
      user = msg.split(sep)[3]   
      return {'AdminCommand': ['stopClient', user]}

   def on_SYNC(self, msg):
      #return {'sync': True}
      return {'AdminCommand': ['sync']}

   def on_Focus(self, msg):
      act=msg.split(sep)[3]
      if str(act) == 'Auto':
         return {'focus'+str(act): True}
      else:
         return {'AdminCommand': ['focus'+str(act)]}

   def on_URLMeteo(self, msg):
      log.info("Meteo: "+msg.split(sep)[3])
      return {'MeteoUrl': True}

   def on_crossOn(self, msg):
      log.info("Pointer: "+msg.split(sep)[3]+" "+msg.split(sep)[4])
      return {'setPointer': [msg.split(sep)[3], msg.split(sep)[4]]}

   def on_Pong(self, msg):
      return {'PongReceived': True}

   def on_TeleStatus(self, msg):
      return {'isTeleFree': True}

   def on_StramingStatus(self, msg):
      return {'getStreamingStatus': True}

   def on_PhotoRunning(self, msg):
      try:
         return {'isPhotoRunning': msg.split(sep)[3]}
      except:
         return {'isPhotoRunning': '0'}

def write(first="null", second="null", third="null", msgfrom=deffrom):
   line=linestart+msgfrom+sep+first+sep+second+sep+third+linestop
   return line.replace(chr(220), '\n')

def chatMessage(msg='', msgfrom=deffrom):
   return write('ChatMessage', msg, 'null', msgfrom)

def privMessage(msg='', msgfrom=deffrom):
   return write('Messaggio', msg, 'null', msgfrom)

def htmlMessage(msg='', msgfrom=deffrom, w='530', h="510"):
   return write('HtmlMessage', msg, w+sep+h, msgfrom)

def bigLive():
   return write("BigLive", deffrom)

def openLink(link='', msgfrom=deffrom):
   return write('OpenWebLink', link, 'null', msgfrom)

def prewelcome(version="null", ntel='0'):
   return write('Versione', version)+write('NTel', ntel)+write('RequestData')

def sendlist(listname, listcont):
   return write(listname, ";".join(listcont))

def welcome():
   return chatMessage('Benvenuti nella chat Skylive - Welcome in Skylive chat')

def setUsername(username):
   return write('YourName', username)

def userlist(users):
   userlist = "*!*".join(users)+'*!*'
   return write('UserList', userlist)

def reqauth():
   return write('RequestData')

def loginmsg(state, perms):
   if state == 'UNAUTH':
       return write('Autorizzazione', 'NonTrovato')
   else:
      if perms['general']['enabled'] == True:
         admin='null'
         try:
            if perms['general']['admin'] == True:
               admin = 'Admin'
         except:
            pass
         return write('Autorizzazione', 'Abilitato', admin)
      else:
         return write('Autorizzazione', 'NonAbilitato')

def statusmsg(status='Unknown', ephem='00:00:0-00.00'):
   return write('Status', status+"**"+ephem)

def ccdtempmsg(temp='-00,0000'):
   return write('CCDTEMP', temp)

def meteo(url='http://127.0.0.1/'):
   return write('UrlMeteo', url)

def photoYes():
   return write('PhotoReadyYES')

def photoNo():
   return write('PhotoReadyNO')

def telescopeFeatures(tname, ccdname, filters, fov, focal):
   return write('TelescopeFeat', tname+'**'+ccdname+'**'+filters+'**'+fov+'**'+focal)

def DomeStatus(dome='Closed'):
   return write('Dome', dome)

def WheatherStatus(wheat='Unknown'):
   return write('Wheather', wheat)

def setObject(object='Unknown'):
   return write('Object', object)

def setLonLat(lon='Unknown', lat='Unknown'):
   return write('LonLat', lon+'**'+ lat)

def guideErr(X, Y):
   return write('GuideError', X, Y)

def ping():
   return write('Ping', str(int(time.time())))
   #return write('Ping', int(time.time()))

def Pointer(x, y):
   return write('setCross', x, y)

def teleOn():
   return write('TeleON')

def teleOff():
   return write('TeleOFF')

def TeleFREE():
   return write('TeleFree')

def TeleBUSY():
   return write('TeleBusy')

def TeleBINNING(binlist):
   return write('TeleBinning', binlist)

def stopClient():
   return write('StopClient')

def TelescopeLiveUri(turi, tint):
   return write('TelescopeLiveUri', "**".join(turi), str(tint))

def ExposureNone():
   return write('ExposureNone')

def ExposureUpload(rem, filter, bin, exp, nick):
   return write('ExposureUpload', "**".join([str(filter), str(bin), str(exp), str(rem)]), str(nick))

def ExposureRunning(rem, filter, bin, exp, nick):
   return write('ExposureRunning', "**".join([str(filter), str(bin), str(exp), str(rem)]), str(nick))

def fwhm(data):
   return write('setFWHM', data)

def StreamStatus(status, forced=False):
   if not forced:
      return write('Streaming', status)
   else:
      return write('ForceStreaming', status)

