import plenario
import weather

import metar
from metar.metar import Metar, ParserError
from plenario.database import task_session as session, task_engine as engine, Base
from sqlalchemy import Table, select, func, and_, distinct
from sqlalchemy import event
from sqlalchemy.engine import Engine
import sys
#import grequests
import requests

import pdb
from lxml import etree
from lxml.etree import fromstring
from cStringIO import StringIO
from lxml import objectify

# Example METAR URL: 'https://aviationweather.gov/adds/dataserver_current/httpparam?datasource=metars&requesttype=retrieve&format=xml&hoursBeforeNow=1.25&stationString=KORD'

current_METAR_url = 'http://aviationweather.gov/adds/dataserver_current/current/'

# An example code:
# - In this example, we have "few clouds at 1500 feet, broken clouds at 4,000 feet w/ cumulonimbus,
#   broken at 6,500 feet, overcast at 20,000 feet"
# - Visibility is 2 statute miles
#code = "METAR KEWR 111851Z VRB03G19KT 2SM R04R/3000VP6000FT TSRA BR FEW015 BKN040CB BKN065 OVC200 22/22 A2987 RMK AO2 PK WND 29028/1817 WSHFT 1812 TSB05RAB22 SLP114 FRQ LTGICCCCG TS OHD AND NW-N-E MOV NE P0013 T02270215"

def getMetar(metar_string):
    m =  Metar(metar_string)
    return m

def all_callSigns():
    sql = "SELECT call_sign FROM weather_stations ORDER by call_sign"
    result=engine.execute(sql)
    return [x[0] for x in result.fetchall()]


def callSign2Wban(call_sign):
    sql = "SELECT wban_code FROM weather_stations where call_sign='%s'" % call_sign
    result = engine.execute(sql)
    #print "result=", result
    x = result.first()
    wban = None
    if x:
        wban = x[0]
        #print "wban=", wban
        #print "found call sign:", call_sign, "wban=", wban
        return wban
    else:
        #print "could not find call sign:", call_sign
        return None

def wban2CallSign(wban_code):
    sql = "SELECT call_sign FROM weather_stations where wban_code='%s'" % wban_code
    result = engine.execute(sql)
    #print "result=", result
    x = result.first()
    cs = None
    if x:
        cs = x[0]
        #print "wban=", wban
    else:
        print "could not find wban:", wban_code
    return cs
        

def getCurrentWeather(call_signs=None, wban_codes=None, all_stations=False, wban2callsigns=None):
    xml_METAR_url = 'http://aviationweather.gov/adds/dataserver_current/httpparam?datasource=metars&requesttype=retrieve&format=xml&hoursBeforeNow=1.25'
    # Example of multiple stations: https://aviationweather.gov/adds/dataserver_current/httpparam?datasource=metars&requesttype=retrieve&format=xml&hoursBeforeNow=1.25&stationString=KORD,KMDW

    if (all_stations == True):
        # We should grab our list from weather_stations and only ask for 100 at a time. 
        #print "all_callSigns is ", all_callSigns()
        #print "len(all_callSigns) is ", len(all_callSigns())
        # XXXXXX TOOO
        pass
    elif (call_signs and wban_codes):
        print "error: define only call_signs or wban_codes and not both"
    elif (wban_codes):
        # Convert all wban_codes to call_signs
        if (wban2callsigns):
            call_signs = []
            for wban in wban_codes:
                if wban in wban2callsigns:
                    call_signs.append(wban2callsigns[wban])
        else:
            call_signs = []
            for wban_code in wban_codes:
                call_sign = wban2CallSign(wban_code)