
import xml.sax
import requests
import json
import sys, getopt
import os

epsgrams = {
    "15_days"           : "classical_15d",
    "15_days_with_clim" : "classical_15d_with_climate",
    "10_days"           : "classical_10d",
    "10_days_wave"      : "classical_wave",
    "10_days_plumes"    : "classical_plume",

}

class MetgramHandler( xml.sax.ContentHandler ):
   def __init__(self):
      self.CurrentData = ""
      self.type = ""
      self.date = ""
      self.expver = ""
      self.stations = []


   # Call when an element starts
   def startElement(self, tag, attributes):
      self.CurrentData = tag
      if tag == "eps":
         self.type = attributes["template"]
         self.date = attributes.get("date", "").strip()
         self.time = attributes.get("time", "").strip()
         if ( self.time != "") :
            self.time = self.time[:2]
         self.expver = attributes.get("expver", "0001")
         self.stations = []
         if self.date == "latest":
            self.date = ""
         else:
            self.date = "%s%s" % (self.date, self.time)


      if tag == "station":

         request =  {
            "station_name" :  attributes["name"],
            "lat" :  attributes["latitude"].strip(),
            "lon" :  attributes["longitude"].strip(),
            "token" : "metview",
            "expver" : self.expver,
            "epsgram" : epsgrams[self.type]
         }
         if attributes.has_key("height") :
            request["altitude"] =  attributes["height"],

         if self.date != "" :
            request["time"] = self.date

         if attributes.has_key("pngfile") :
            request["format"] = "png"
            output =  attributes["pngfile"]
         if attributes.has_key("psfile") :
            request["format"] = "ps"
            output =  attributes["psfile"]
         if attributes.has_key("pdffile") :
            request["format"] = "pdf"
            output =  attributes["pdffile"]
         self.stations.append({"request" : request,
                "output": output}
            )



   # Call when an elements ends
   def endElement(self, tag):
      if tag == "eps":


         self.execute()



   # Call when a character is read
   def characters(self, content):
      pass

   def execute(self):
        url = "https://apps.ecmwf.int/plots/product-download/web/classical_meteogram"
        for station in self.stations :
            request = station["request"]
            request["token"]           = "metview" # this token will only work from inside ECMWF
            request["email"]           = "Web.Administrator@ecmwf.int"
            request["generator"]       = "Metview"
            request["metview_version"] = os.environ["METVIEW_RELEASE"]
            request["metview_user"]    = os.environ["USER"]
            request = requests.get(url, params = request,
            proxies = { "http":  "http://proxy.ecmwf.int:3333/", 
                        "https": "http://proxy.ecmwf.int:3333/" })
            print request.url
            if request.status_code == 200 :
                out = open(station["output"], "w")
                out.write(request.content)
                out.close()
                print "Result saved in %s" % (station["output"], )
            else :
                print "No Result -->Error %d" % (request.status_code)
        self.stations = []


def main(argv):
    try:
      opts, args = getopt.getopt(argv,"hi:",["input="])
    except getopt.GetoptError:
      print 'metgram.py -i <inputfile> '
      sys.exit(2)
    for opt, arg in opts:
      if opt == '-h':
         print 'metgram.py -i <inputfile> '
         sys.exit()
      elif opt in ("-i", "--input"):
         input = arg

   # create an XMLReader
    parser = xml.sax.make_parser()
   # turn off namepsaces
    parser.setFeature(xml.sax.handler.feature_namespaces, 0)

   # override the default ContextHandler
    Handler = MetgramHandler()
    parser.setContentHandler( Handler )

    parser.parse(input)

if __name__ == "__main__":
   main(sys.argv[1:])
