#!/usr/bin/env python
# -*- coding: utf-8 -*-

# 0.2: gestion d'un BMS
# 0.1: first release

"""
pyGetMeteo : Compilation de donnees meteo
 necessite wget, iconv
 http://kubuntu.free.fr/blog/index.php/2007/05/21/215-pygetmeteo-compilation-de-donnees-meteo-locales-sur-une-seule-page
"""
__author__ = "JJL <BuggerOne@gmail.com>"
__copyright__ = "Copyright (c) 2007 JJL"
__license__ = "GPL"
__version__ = "0.2"
__date__ = "$Date: $"

import os,re,time,sys

### Parametres a modifier ###

# meteo marine
# http://www.meteofrance.com/FR/mer/bulCote.jsp?LIEUID=COTE_HAGU_PENM
# http://www.meteofrance.com/FR/mer/bmsCote.jsp?LIEUID=COTE_HAGU_PENM
lieu_meteo="COTE_HAGU_PENM"
# marée du port
# http://www.shom.fr/ann_marees/cgi-bin/predit_ext/choixp?opt=&zone=11&port=0&portsel=list
lieu_maree="TREBEURDEN"
# meteo departementale
# http://www.meteofrance.com/FR/mameteo/prevDept.jsp?LIEUID=DEPT22
lieu_meteo_dep='DEPT22'
# prevision satellite
# http://www.meteofrance.com/FR/mameteo/prevSatEurope.jsp?LIEUID=EUROPE
lieu_meteo_sat='EUROPE'

# repertoire destination
outputdir="./"
# fichiers destination
outputhtml=outputdir+"index.html"
outputimg=outputdir+"maree.gif" # hauteur d'eau (SHOM)
outputsat=outputdir+"meteosat.jpg" # prevision sat (Meteo France)

### Fin des parametres a modifier ###

# fichiers temporaires
temp1="/tmp/meteofr.html" # meteo marine
temp2="/tmp/mareeshom.html" # maree
temp3="/tmp/meteosat.html" # prevision sat

def erreur(msg):
   """ affiche un message d'erreur """
   print >>sys.stderr,"###",msg

def info(msg):
   """ affiche un message """
   print "***",msg

if __name__ == "__main__":
   # parametres de la page HTML
   data={"meteo":"",
         "maree":"",
         "departement":lieu_meteo_dep,
         "satimage":os.path.basename(outputsat),
         "date":time.strftime("%d/%m/%Y &agrave; %H:%M"),
         "linkmarine":"http://www.meteofrance.com/FR/mer/bulCote.jsp?LIEUID=%s"%(lieu_meteo),
         "linkmarinebms":"http://www.meteofrance.com/FR/mer/bmsCote.jsp?LIEUID=%s"%(lieu_meteo),
         "linksat":"http://www.meteofrance.com/FR/mameteo/prevSatEurope.jsp?LIEUID=%s"%(lieu_meteo_sat),
         "linkshom":"http://www.shom.fr/ann_marees/cgi-bin/predit_ext/choixp?opt=10&zone=11&port=%(lieu)s&dd=%(jour)s&mm=%(mois)s&yyyy=%(annee)s&compute=TRUE&fuseau=2"
            %{'lieu':lieu_maree,'jour':time.strftime("%d"),'mois':time.strftime("%m"),'annee':time.strftime("%Y")},
         "version":__version__
      }

   # Meteo marine sur le site de meteo france
   info("Meteo marine ...")
   os.system("""wget -nv "%s" -O %s"""%(data['linkmarine'],temp1))
   fin = file(temp1,"r")
   r = re.compile("""<table width="406" height="14" border="0" cellpadding="0" cellspacing="3">(.*?)</table>""",re.DOTALL)
   m = r.findall(fin.read())
   if (m):
      if len(m) == 1:
         data['meteo'] = m[0]
      else:
         # BMS en cours
         os.system("""wget -nv "%s" -O %s"""%(data['linkmarinebms'],temp1+"bms"))
         finbms = file(temp1+"bms","r")
         r = re.compile("""<td class="titrAlert" colspan=2>(.*?)</td>""",re.DOTALL)
         m2 = r.findall(finbms.read())
         if (m2):
            data['meteo'] = "<h3>BMS</h3>"+m2[0]
         else:
            data['meteo'] = ""
            erreur('cannot find BMS')
         data['meteo'] += "<h3>Bulletin</h3>"+m[1]
         finbms.close()
   else:
      erreur("cannot find meteo")
   fin.close()

   # image satellite prevue
   info("Prevision satellite ...")
   os.system("""wget -nv "%s" -O %s """%(data['linksat'],temp3))
   fin = file(temp3,"r")
   r = re.compile("""<img src="(/img/produits/sat/eur/.*?)" """,re.DOTALL)
   m = r.search(fin.read())
   if (m):
      sat=m.groups()[0]
      os.system ("""wget -nv "http://www.meteofrance.com%s" -O %s"""%(sat,outputsat))
   else:
      erreur("cannot find sat image")
   fin.close()

   # maree sur le site du shom
   info("Maree ...")
   os.system("""wget -nv "%s" -O %s"""
               %(data['linkshom'],temp2))
   fin = file(temp2,"r")
   # tableau de maree
   r = re.compile("""<table border=1 bgcolor=#AFEEEE cellpadding=10 width=100%>(.*?</table>.*?)</table>""",re.DOTALL)
   m = r.search(fin.read())
   if (m):
      maree = m.groups()[0]
      # image de hauteur d'eau
      r = re.compile("""img src *= *"(.*?)">""",re.DOTALL)
      m=r.search(maree)
      if (m):
         maree_image=m.groups()[0]
         os.system("""wget -nv "http://www.shom.fr%s" -O %s"""%(maree_image,outputimg))
         maree = maree.replace(maree_image,os.path.basename(outputimg))
      else:
         erreur ("cannot find maree image")
      data['maree']=maree
   else:
      erreur("cannot find maree")
   fin.close()

   # creation fichier de sortie
   info ("Generation du fichier ...")
   fout=file(outputhtml,"w")
   fout.write("""
   <?xml version="1.0" encoding="UTF-8"?>
   <html>
      <head>
         <META http-equiv=Content-Type content="text/html; charset=UTF-8">
         <title>Compilation meteo</title>
      </head>
      <body>
         <h1>Compilation des donn&eacute;es m&eacute;t&eacute;o</h1>
         <table><tr><td colspan=2 align=center>
            <table>%(maree)s</table>
         </td></tr>
         <tr><td>
            <h2>M&eacute;t&eacute;o Marine</h2>
            <table>%(meteo)s</table>
         </td><td valign=top>
            <h2>Pr&eacute;vision Sat</h2>
            <img src=%(satimage)s >
            <h2>Pr&eacute;vision M&eacute;t&eacute;o</h2>
            <iframe marginwidth='0' marginheight='0' align='left' valign='top' frameborder='0' height='505' width='406' scrolling='no'
               src='http://www.meteofrance.com/FR/mameteo/prevDept_iframe.jsp?LIEUID=%(departement)s' name="cartePrev" id="cartePrev" >
            </iframe>
         </td>
         </tr>
         </table>
         <hr/>
         M&eacute;t&eacute;o marine de <a href="%(linkmarine)s">M&eacute;t&eacute;o France</a><br/>
         Image satellite de <a href="%(linksat)s">M&eacute;t&eacute;o France</a><br/>
         Mar&eacute;es du <a href="%(linkshom)s">SHOM</a><br/>
         Page g&eacute;n&eacute;r&eacute;e le %(date)s, version: %(version)s
      </body>
   </html>"""%data)
   fout.close()

   # conversion en UTF-8
   os.system("iconv -f ISO-8859-1 -t UTF-8 -o %s.utf8 %s"%(outputhtml,outputhtml))
   os.system("mv %s.utf8 %s"%(outputhtml,outputhtml))

