#!/usr/bin/python 
# -*- coding: iso-8859-15 -*-

#
#----------------------------------------------------------------------------------------------------
#
#  scexevent:  1) returns identifier of new seismic event(s).
#      SC3 utility scevtls is used to generate identifier's list
#      and to compare it with the list already registered (one file per year/month).
#      If there is a difference, a new event has occured. The advantage is that
#      events are stored in small files, one per month.
#         2) alert userlist by sms or email.
#      For sending sms is needed any gsm modem connected via serial cable on
#      any ttyS(n) changed the MODEM parameter and setting BAUDRATE as you whant
#      (default: MODEM = /dev/ttyS0; BAUDRATE = 19200
#      For sending email is used free sendEmail downloadable by
#      http://caspian.dotconf.net/menu/Software/SendEmail/
#         3) store mseed wave format, according with NETWORK, in folders 
#      separated by year/month/day
#      (default: ~seiscomp3/wave/mseed/YYYY/MM/DD/time_of_event.mseed).
#         4) convert mseed waves in sac waves and compress in a file
#      (default: ~seiscomp3/wave/sac/YYYY/MM/DD/time_of_event.sac.tar).
#      To convert mseed to sac is used free mseed2sac (Chad Trabant)
#      downloadable from http://www.iris.edu/pub/programs/converters/
#         5) store waveform data in other local folder or in remote computer folder 
#      to make backup files
#         6) generate an XML events quake file and transfer it via ftp
#      (this format is adjusted for www.binapg.it site. You can modify 
#      the source phython file "scmakexml" at your own risk)
#         7) If you manually calculate an event and this action change it's parameters,
#      the script riextract the newer event waves and delete the oldest
#
#  Date: 31/06/2011, author: Sergio Tardioli, Osservatorio Sismico "A.Bina" Perugia, Italy
#        mail s.tardioli@binapg.it
#
#  PYTHON script based on SC3NewEventEnglish.sh bash script of Pierre Lebellegard, IRD Noumea, New Caledonia
#
#  To run this script you must have this script:
#  scnewevents  : this script
#  scmakexml  : the script to make xml files
#  sendEmail  : the program to send mail:
#  mseed2sac  : the program to convert mseed to sac waveform
#  Global    : the file with global parameter
#  scsendftp  : to sending xml file to remote computer via ftp
#  scmetadata  : to create metadata used by mseed2sac to convert waveform.
#        To automatically run scmetadata when you change the station parameters in seiscomp,
#        you can add the link in seiscomp script at the end of _write_conf() function
#  You can add the link to crontab to automatically run this script
#
#----------------------------------------------------------------------------------------------------
#


#from Global import *
print 'inizio lavoro\n'
import sys
import os
sys.path.append(os.path.dirname(__file__))
#sys.stdout.write('Aggiornato il path\n')
import time
import locale
import MySQLdb
from expand import expand_var,find_value_seiscomp
from optparse import OptionParser
from datetime import datetime,date,timedelta
import glob
DateSc='%Y/%m/%d %H:%M:%S'
print 'caricato tutto\n'
TxtBlk='\x1B[0;29m' # Nero - Regular
TxtGry='\x1B[0;30m' # Grigio
TxtRed='\x1B[0;31m' # Rosso
TxtGrn='\x1B[0;32m' # Verde
TxtYlw='\x1B[0;33m' # Giallo
TxtBlu='\x1B[0;34m' # Blu
TxtPur='\x1B[0;35m' # Viola
TxtCyn='\x1B[0;36m' # Ciano
TxtWht='\x1B[0;37m' # Bianco
BldBlk='\x1B[1;29m' # Nero - Bold
BldGry='\x1B[1;30m' # Grigio
BldRed='\x1B[1;31m' # Rosso
BldGrn='\x1B[1;32m' # Verde
BldYlw='\x1B[1;33m' # Giallo
BldBlu='\x1B[1;34m' # Blu
BldPur='\x1B[1;35m' # Viola
BldCyn='\x1B[1;36m' # Ciano
BldWht='\x1B[1;37m' # Bianco
UnkBlk='\x1B[4;29m' # Nero - Underline
UnkGry='\x1B[4;30m' # Grigio
UndRed='\x1B[4;31m' # Rosso
UNdGrn='\x1B[4;32m' # Verde
UndYlw='\x1B[4;33m' # Giallo
UndBlu='\x1B[4;34m' # Blu
UndPur='\x1B[4;35m' # Viola
UndCyn='\x1B[4;36m' # Ciano
UndWht='\x1B[4;37m' # Bianco
BlkBlk='\x1B[5;29m' # Nero - Blinking
BlkGry='\x1B[5;30m' # Grigio
BlkRed='\x1B[5;31m' # Rosso
BlkGrn='\x1B[5;32m' # Verde
BlkYlw='\x1B[5;33m' # Giallo
BlkBlu='\x1B[5;34m' # Blu
BlkPur='\x1B[5;35m' # Viola
BlkCyn='\x1B[5;36m' # Ciano
BlkWht='\x1B[5;37m' # Bianco
BakBlk='\x1B[40m'   # Nero - Background
BakRed='\x1B[41m'   # Rosso
BadGrn='\x1B[42m'   # Verde
BakYlw='\x1B[43m'   # Giallo
BakBlu='\x1B[44m'   # Blu
BakPur='\x1B[45m'   # Viola
BakCyn='\x1B[46m'   # Ciano
BakWht='\x1B[47m'   # Bianco
TxtRst='\x1B[0m'    # Text Reset
Txtdef='\x1B[39m'
Default_Color=TxtBlk
print 'impostati colori\n'
Seiscomp_Root = expand_var('SEISCOMP_ROOT')
configuration_directory=['etc/defaults','etc','~/.seiscomp3']
DefLanguage='it_IT'
SepCharUser = ''
AccComp = "%."+str(2)+"f"
loc = locale.getdefaultlocale()
locale.setlocale(locale.LC_ALL, DefLanguage)
#sys.path.insert(0, Seiscomp_Root+'/bin')

Global=Seiscomp_Root+'/trunk/key/global'
reqhandler=Seiscomp_Root+'/trunk/config/reqhandler.cfg'
scmaster=Seiscomp_Root+'/trunk/config/scmaster.cfg'
print 'impostate variabili\n'
now = time.gmtime()
EndDate = datetime(now.tm_year,now.tm_mon,now.tm_mday)+timedelta(days = 1)
StartDate = datetime(now.tm_year,now.tm_mon,1)
query='select PEvent.publicID, Magnitude.magnitude_value, Magnitude.type, Origin.latitude_value, Origin.longitude_value, Origin.time_value, Origin.evaluationStatus, Origin.evaluationMode from Origin, Magnitude, Event, PublicObject as POrigin, PublicObject as PMagnitude, PublicObject as PEvent where Magnitude._oid=PMagnitude._oid and Event.preferredOriginID=POrigin.publicID and Event.preferredMagnitudeID=PMagnitude.publicID and Origin._oid=POrigin._oid and Event._oid=PEvent._oid and Magnitude._parent_oid=Origin._oid and POrigin.publicID=Event.preferredOriginID '
global MagMin
MagMin=0
print 'arrivato alla fine delle dichiarazioni\n'
def getKey(item):
  return item[0]
def get_querry():
#  Year = StartDate.tm_year
#  Month = StartDate.tm_mon
#  Day = StartDate.tm_mday
#EndDate = datetime(now.tm_year,now.tm_mon,now.tm_mday)-timedelta(days = EventBackDays)
#  d = datetime(Year, Month, Day)-timedelta(days = EventBackDays)
  db = MySQLdb.connect(host = host_con,user = user_con,passwd = password_con,db = db_table)
  cursor = db.cursor()
  #print query+' and Origin.time_value between "%s" and "%s" and  Magnitude.magnitude_value >= %s;'%(StartDate,EndDate,float(MagMin))
  cursor.execute(query+' and Origin.time_value between "%s" and "%s" and  Magnitude.magnitude_value >= %s;'%(StartDate,EndDate,float(MagMin)))
#  cursor.execute('select PEvent.publicID, Magnitude.magnitude_value, Magnitude.type, Origin.latitude_value, Origin.longitude_value, Origin.time_value, Origin.evaluationStatus from Origin, Magnitude, Event, PublicObject as POrigin, PublicObject as PMagnitude, PublicObject as PEvent where Magnitude._oid=PMagnitude._oid and Event.preferredOriginID=POrigin.publicID and Event.preferredMagnitudeID=PMagnitude.publicID and Origin._oid=POrigin._oid and Event._oid=PEvent._oid and Magnitude._parent_oid=Origin._oid and POrigin.publicID=Event.preferredOriginID and Origin.time_value between "%s" and "%s" and  Magnitude.magnitude_value >= %s;'%(StartDate,EndDate,float(MagMin)))
  row = cursor.fetchall()
  cursor.close()
  db.close()
  return row

def Start_Work():
  ListEv = []
  row = get_querry()
  row=sorted(row, key=getKey)  
  for Sta_Item in range(len(row)):
    print row[Sta_Item][0]+' '+AccComp%(float(abs(row[Sta_Item][3]))),
    if row[Sta_Item][3]>0:
      print 'N',
    else:
      print 'S',
    print AccComp%(float(abs(row[Sta_Item][4]))),
    if row[Sta_Item][4]>0:
      print 'E',
    else:
      print 'W',
    print row[Sta_Item][5],
    if isinstance(options.magmin,float):
      print '%1.2f %s'%(row[Sta_Item][1],row[Sta_Item][2]),
    if row[Sta_Item][6]=='confirmed':
      if row[Sta_Item][7]=='automatic':
        print 'C',
      else:
        print 'M',
    else:
      print 'A',
    print

def Return(Value):
   return Value

def main(argv):
  global options
  global query
  parser = OptionParser()
  parser.add_option('-d', '--date', type='string', dest='DateEvent', help='Range date to search in format "YYYY/MM/DD HH:MM:SS-YYY/MM/DD HH:MM:SS". Date is intended as FROM DATE "YYYY/MM/DD HH:MM:SS" TO DATE (note the "-" separator between the two dates) "YYYY/MM/DD HH:MM:SS". You can also enter only one date, that is intended as "FROM" date."TO DATE" is current date. Is possible to enter only date without time.')
  parser.add_option('-a', '--accuracy', type='int', dest='AccuracyComp', help='Accuracy lat lon output')
  parser.add_option('-b', '--backdays', type='float', dest='backdays', help='How many days before current date (it do not work if -d flag is use')
  parser.add_option('-m', '--magmin', type='float', dest='magmin', help='Minimum magnitude. Default 0')
  parser.add_option('-t', '--type', type='string', dest='type', help='Type of event to extract without space (default all type Automatic, Manual, Confirmed [AMC])')
  try:
    (options, args) = parser.parse_args()
  except:
    sys.exit(-1)
  if len(argv) > 1:
#    def exit_on_error():
#      parser.print_help()
#      sys.exit()
    if len(args)>0:
      print '\nWARNING:\n\n  EXTRA OPTION DETECTED\n'
      for arg in range(len(args)):
        print '%s'%str(args[arg],)
      print '\n'
      sys.exit(-1)
    write=False
    if isinstance(options.type,str):
      typel=options.type.split(',')
      typel=[element.upper() for element in typel]

      if "A" in typel:
        query+=' and '
        if not "C" in typel:
          print len(typel)
          if len(typel)>1:
            query+='('
          query+='(Origin.evaluationMode = "automatic" and Origin.evaluationStatus is NULL)'
        else:
          typel.remove("C")
          if len(typel)>1:
            if "M" in typel:
              query+='('
          query+='Origin.evaluationMode = "automatic"'          

      if "M" in typel:
        if "C" in typel:
          query+='and ((Origin.evaluationMode = "automatic" and Origin.evaluationStatus = "confirmed")'
          typel.remove("C")
        if len(typel)>1:
          query+=' or'
        else:
          query+=' and'
        query+=' Origin.evaluationMode = "manual"'
        if len(typel)>1:
          query+=')'
      if "C" in typel:
        query+=' and (Origin.evaluationMode = "automatic" and Origin.evaluationStatus = "confirmed")'
#    print query
    if isinstance(options.DateEvent,str):
      global StartDate
      global EndDate
      try:
        try:
          d = time.strptime(options.DateEvent.split('-')[0],DateSc.split()[0])
        except:
          d = time.strptime(options.DateEvent.split('-')[0],DateSc)
        StartDate = datetime(d.tm_year,d.tm_mon,d.tm_mday,d.tm_hour,d.tm_min,d.tm_sec)
        try:
          d = time.strptime(options.DateEvent.split('-')[1],DateSc.split()[0])
        except:
          d = time.strptime(options.DateEvent.split('-')[1],DateSc)
        EndDate = datetime(d.tm_year,d.tm_mon,d.tm_mday,d.tm_hour,d.tm_min,d.tm_sec)+timedelta(days = 1)
      except:
        try:
          d = time.strptime(options.DateEvent,DateSc.split()[0])
        except:
          d = time.strptime(options.DateEvent,DateSc)
        StartDate = datetime(d.tm_year,d.tm_mon,d.tm_mday,d.tm_hour,d.tm_min,d.tm_sec)
    if isinstance(options.backdays,float):
      if isinstance(options.DateEvent,str):
        print 'Your -d selection will decay..\nYou can\'t use -b and -d selection'
#        print TxtBlk+'Your '+BldRed+'-d'+TxtBlk+' selection will decay..\nYou can\'t use '+BldRed+'-b'+TxtBlk+' and '+BldRed+'-d'+TxtBlk+' selection'+Default_Color
      StartDate = datetime(now.tm_year,now.tm_mon,now.tm_mday,now.tm_hour,now.tm_min,now.tm_sec)-timedelta(days = options.backdays)
    if isinstance(options.magmin,float):
      global MagMin
      MagMin=options.magmin
    if isinstance(options.AccuracyComp,int):
      global AccComp
      AccComp = "%."+str(options.AccuracyComp)+"f"
    Start_Work()
  else:
    parser.print_help()
if __name__ == '__main__':


  loc = locale.getdefaultlocale()
  tmp_folder = '/tmp'
  tmp_file = '/scexdata.tmp'
  Organization=find_value_seiscomp('organization')
  DirArchivio=find_value_seiscomp('archive')
  readConnection=find_value_seiscomp('plugins.dbPlugin.readConnection')

  user_con = readConnection.split(':')[0]
  password_con = readConnection.split('@')[0].split(':')[1]
  host_con = readConnection.split('@')[1].split('/')[0]
  db_table = readConnection.split('@')[1].split('/')[1]

  DBDriver= find_value_seiscomp('plugins.dbPlugin.dbDriver')
  DBReadConn = find_value_seiscomp('plugins.dbPlugin.readConnection')

  """
  for Item in range(0,len(configuration_directory)-1):
    if configuration_directory[Item][0]!='~':
      curdir=Seiscomp_Root+'/'+configuration_directory[Item]
    else:
      curdir=expanduser(configuration_directory[Item])
    return_value=find_value_seiscomp('organization')
    if return_value!=None:
      Organization=return_value
  print Organization
  sys.exit()
  try:
    req = open(reqhandler,'r')
    for row in req:
      if ('organization' in row) & (row[0] != '#'):
        Organization = row.split('=')[1][2:len(row.split('=')[1])-2]
      if ('nrtdir' in row) & (row[0] != '#'):
        DirArchivio = row.split('"')[1]
    req.close()
  except:
    sys.stderr.write(os.path.basename(__file__)+' This program can\'t run because is impossible to retrieve '+reqhandler.split('/')[len(reqhandler.split('/'))-1])
    sys.exit(1)
  try:
    req = open(scmaster,'r')
    for row in req:
      if 'plugins.dbPlugin.readConnection' in row:
        readConnection = row.split('=')
        user_con = readConnection[1].split(':')[0].split('"')[1]
        password_con = readConnection[1].split('@')[0].split(':')[1]
        host_con = readConnection[1].split('@')[1].split('/')[0]
        db_table = readConnection[1].split('@')[1].split('/')[1].split('"')[0]      
    req.close()  
  except:
    sys.stderr.write(os.path.basename(__file__)+' This program can\'t run because is impossible to retrieve '+scmaster.split('/')[len(scmaster.split('/'))-1])
    sys.exit(1)
  try:
    req = open(Global,'r')
    for row in req:
      if 'DB_DRIVER' in row:
        DBDriver = row.split('=')[1].strip('\n').strip("'")
      if 'DB_READ_CONNECTION' in row:
        DBReadConn = row.split('=')[1].strip('\n').strip("'")
    req.close()
    DataBase = DBDriver+'://'+DBReadConn
  except:
    sys.stderr.write(os.path.basename(__file__)+' This program can\'t run because is impossible to retrieve '+Global.split('/')[len(Global.split('/'))-1])
    sys.exit(1)
  """
  main(sys.argv)
  locale.setlocale(locale.LC_ALL, loc)
  sys.exit()

