#!/usr/bin/mython

# Copyright (C) 2009 Thomas Baleno
#
#        tbaleno@usa.net
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -- 
#
# File: weatherapp.py
# Author: Thomas Baleno
# Maintainer: Thomas Baleno
# Version: 1.0b
# Description: This program reads your location from gpsd and reports near current conditions.
#


from HTMLParser import HTMLParser, HTMLParseError
import gps, os, time, urllib, urlparse, re
import wx
import wx.html
import cStringIO

session = gps.gps()
session.query('admosy')
time.sleep(2)

class MyHtmlFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, -1, title, size=wx.DisplaySize())
        screen = wx.Bitmap("loading.jpg",wx.BITMAP_TYPE_JPEG)
        wxID_BUTTON = wx.NewId()
        #self.mysplasy.Show(true)
        wx.Yield()
        self.html = wx.html.HtmlWindow(self)
        if "gtk2" in wx.PlatformInfo:
            self.html.SetStandardFonts()
        # a = altitude, d = date/time, m=mode,
        # o=postion/fix, s=status, y=satellites

        self.button = wx.Button(id=wxID_BUTTON, label=u'UPDATE',name="refresh",parent=self.html,pos=wx.Point(0,0),size=wx.Size(100,80),style=0)
        self.button.Bind(wx.EVT_BUTTON, self.OnButton, id=wxID_BUTTON)

        self.refreshpage()

    def OnButton(self,evt):
        self.refreshpage()

    def refreshpage(self):
        while (session.fix.latitude == 0.0):
            session.query('admostyv')
            wx.Yield()
            print "polling", session.fix.latitude
            time.sleep(1)
        wx.Yield()

        self.htmlPage = "http://forecast.weather.gov/MapClick.php?textField1="+str(session.fix.latitude) +"&textField2="+str(session.fix.longitude)
        self.SetTitle("Weather for: " +str(session.fix.latitude)+","+str(session.fix.longitude))
        sock = urllib.urlopen(self.htmlPage)
        h = sock.read()
        cc = h[h.find("currentconds"):h.find("radandsat")]
        tables = "<" + cc[cc.find("table"):cc.find("/table")] + "/table>"
        self.html.SetPage(tables)

app = wx.PySimpleApp()
frm = MyHtmlFrame(None, "Weather for: " +str(session.fix.latitude)+","+str(session.fix.longitude))
frm.Show()
app.MainLoop()
