#!/usr/bin/env python
#
#    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 3 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, see <http://www.gnu.org/licenses/>.

#
#  If this screenlet is repackaged it should be repackaged with the README included
#  for a history of the changes and improvements made to it.
#

import re
from urllib import urlopen
import screenlets
from screenlets.options import StringOption, BoolOption, ColorOption
from screenlets.options import create_option_from_node
import pygtk
pygtk.require('2.0')
import cairo
import pango
import sys
import gobject
import weatherradar
import gtk
from gtk import gdk

# use gettext for translation
import gettext

_ = screenlets.utils.get_translator(__file__)

def tdoc(obj):
	obj.__doc__ = _(obj.__doc__)
	return obj

@tdoc

class SmoothWeatherScreenlet(screenlets.Screenlet):
	"""A weather screenlet with easier user customization and improved weather information layout.  This screenlet is compatible with any icon pack compatible with weather.com , you can find many packs on deviantart.com or http://liquidweather.net/icons.php#iconsets.  Weather feeds are provided by weather.com"""
	# default meta-info for Screenlets
	__name__ = 'SmoothWeatherScreenlet'
	__version__ = '0.3.1'
	__author__ = 'Casey Trader aka Swiftfeet based on screenlet by Helder Fraga aka Whise'
	__desc__ = __doc__

	# internals
	__timeout = None

	update_interval = 300
	show_error_message = 1

	#width = 132
	#height = 100

	width = 396  ## Took away multiplier of 3 from screenlet dimensions
	height = 300
	#lasty = 0
	#lastx = 0   ## the cursor position inside the window (is there a better way to do this??)
	#over_button = 1

	#theme_name = "default"
	#img_file = None
	ZIP = "53701"
	use_metric = False
	show_daytemp = True
	mini = False
	show_precip = True
	show_visible = False
	show_wind = False
	show_radar = False
	custom_bg = False
	bg_color1 = .3, .5, .6, 1
	bg_color2 = 1, 1, 0, 1
	#radar_border_color = 1, 1, 1, 1

	p_layout = None
	p_layout1 = None
	p_layout2 = None
	latest = []          ## the most recent settings we could get...
	latestHourly = []

	updated_recently = 0 ## don't keep showing the error messages until a connection has been established
			     ## and then lost again.
	
## Local Definitions ##
	
	# constructor
	def __init__(self, text="", **keyword_args):
		#call super (and not show window yet)
		screenlets.Screenlet.__init__(self, width=int(self.width * self.scale), height=int(self.height * self.scale),uses_theme=True, **keyword_args) 
		# set theme
		self.theme_name = "default"		
		# add zip code menu item 
		self.add_menuitem("zipcode", _("Zip Code..."))
		self.add_menuitem("mini", _("Toggle mini-view"))
		self.add_menuitem ("use_metric", unichr(176) + "F / " + unichr(176) + "C")
		self.add_menuitem("show_radar", _("Radar"))
		# add default menu items
		self.add_default_menuitems()
		# init the timeout function
		self.update_interval = self.update_interval
                self.init_options_from_metadata()

	def init_options_from_metadata(self):
                print __file__
                p = __file__.rfind('/')
                mypath = __file__[:p]
                print mypath
                self.add_options_from_file( mypath + '/' + self.__class__.__name__ + '.xml')
	
	# attribute-"setter", handles setting of attributes
	def __setattr__(self, name, value):
		# call Screenlet.__setattr__ in baseclass (ESSENTIAL!!!!)
		screenlets.Screenlet.__setattr__(self, name, value)
		# check for this Screenlet's attributes, we are interested in:
		if name == _("ZIP"):
			self.__dict__[name] = value
			gobject.idle_add(self.update_weather_data)
		if name == "update_interval":
			if value > 0:
				self.__dict__['update_interval'] = value
				if self.__timeout:
					gobject.source_remove(self.__timeout)
				self.__timeout = gobject.timeout_add(value * 1000, self.update)
			else:
				# TODO: raise exception!!!
				pass
		if name == "show_precip":
			self.redraw_canvas()		####This works very nicely for realtime update of options
		if name == "use_metric":
			self.update_weather_data()	####Works, but slight hinder in performance
		if name == "show_daytemp":
			self.redraw_canvas()
		if name == "mini" and self.show_radar == False:  ####Stops radar from messing up mini view
			self.redraw_canvas()	
		if name == "show_wind":
			self.redraw_canvas()
		if name == "show_visible":
			self.redraw_canvas()
		if name == "show_radar" and self.mini == False:  ####Stops radar from messing up mini view
			print "show Radar"
			self.redraw_canvas()	
		if name == "custom_bg":
			self.redraw_canvas()
		if name == "bg_color1":
			self.redraw_canvas()
		if name == "bg_color2":
			self.redraw_canvas()		

	def update(self):
		gobject.idle_add(self.update_weather_data)
		return True


	def update_weather_data(self):
		temp = self.parseWeatherData()
		temp2 = self.parseWeatherDataHourly()
	
		if temp[0]["where"] == '':    ##did we get any data?  if not...
			if self.show_error_message==1 and self.updated_recently == 1:
				self.show_error()
			self.updated_recently = 0
		else:
			self.latest = temp
			self.latestHourly = temp2
			self.updated_recently = 1
			self.redraw_canvas()


	def parseWeatherData(self):
		if self.use_metric:
			unit = 'm'
		else:
			unit = 's'
		data = urlopen('http://xoap.weather.com/weather/local/'+self.ZIP+'?cc=*&dayf=10&prod=xoap&par=1003666583&key=4128909340a9b2fc&unit='+unit).read()
		forecast = []

		dcstart = data.find('<loc ')
		dcstop = data.find('</cc>')     ###### current conditions
		data_current = data[dcstart:dcstop]
		forecast.append(self.tokenizeCurrent(data_current))

		for x in range(10):
			dcstart = data.find('<day d=\"'+str(x))
			dcstop = data.find('</day>',dcstart)   #####10-day forecast
			day = data[dcstart:dcstop]
			forecast.append(self.tokenizeForecast(day))

		return forecast


	def parseWeatherDataHourly(self):
		if self.use_metric:
			unit = 'm'
		else:
			unit = 's'
		data = urlopen('http://xoap.weather.com/weather/local/'+self.ZIP+'?cc=*&dayf=10&prod=xoap&par=1003666583&key=4128909340a9b2fc&unit='+unit+'&hbhf=12').read()
		hforecast = []

		for x in range(8):
			dcstart = data.find('<hour h=\"'+str(x))
			dcstop = data.find('</hour>',dcstart)   ####hourly forecast
			hour = data[dcstart:dcstop]
			hforecast.append(self.tokenizeForecastHourly(hour))

		return hforecast


	def tokenizeForecast(self, data):
	
		day = self.getBetween(data, '<part p="d">', '</part>')
		daywind = self.getBetween(day, '<wind>', '</wind>')
	
		night = self.getBetween(data, '<part p="n">', '</part>')
		nightwind = self.getBetween(night, '<wind>', '</wind>')

		tokenized = {
		'date': self.getBetween(data, 'dt=\"','\"'),
		'day' : self.getBetween(data, 't=\"','\"'),
		'high': self.getBetween(data, '<hi>','</hi>'),
		'low': self.getBetween(data, '<low>','</low>'),	
		'sunr': self.getBetween(data, '<sunr>','</sunr>'),
		'suns' : self.getBetween(data, '<suns>','</suns>'),		
		'dayicon' : self.getBetween(day, '<icon>','</icon>'), 
		'daystate' : self.getBetween(day, '<t>','</t>'), 
		'daywindspeed' : self.getBetween(daywind, '<s>','</s>'), 
		'daywinddir' : self.getBetween(daywind, '<t>','</t>'), 
		'dayppcp' : self.getBetween(day, '<ppcp>','</ppcp>'), 
		'dayhumid' : self.getBetween(day, '<hmid>','</hmid>'),
		'nighticon' : self.getBetween(night, '<icon>','</icon>'), 
		'nightstate' : self.getBetween(night, '<t>','</t>'), 
		'nightwindspeed' : self.getBetween(nightwind, '<s>','</s>'), 
		'nightwinddir' : self.getBetween(nightwind, '<t>','</t>'), 
		'nightppcp' : self.getBetween(night, '<ppcp>','</ppcp>'), 
		'nighthumid' : self.getBetween(night, '<hmid>','</hmid>'),
		}
		return tokenized

	def tokenizeForecastHourly(self, data):
		tokenized = {
		'hour' : self.getBetween(data, 'c=\"','\"'),
		'tmp': self.getBetween(data, '<tmp>','</tmp>'),
		'flik': self.getBetween(data, '<flik>','</flik>'),
		'icon': self.getBetween(data, '<icon>','</icon>')
		}
		return tokenized
	
	def tokenizeCurrent(self, data):
		wind = self.getBetween(data, '<wind>', '</wind>')
		bar = self.getBetween(data, '<bar>', '</bar>')
		uv = self.getBetween(data, '<uv>', '</uv>')

		tokenized = {
		'where': self.getBetween(data, '<dnam>','</dnam>'),
		'time' : self.getBetween(data, '<tm>','</tm>'),
		'sunr': self.getBetween(data, '<sunr>','</sunr>'),
		'suns' : self.getBetween(data, '<suns>','</suns>'),	
		'date' : self.getBetween(data, '<lsup>','</lsup>'),
		'temp' : self.getBetween(data, '<tmp>','</tmp>'),	
		'flik' : self.getBetween(data, '<flik>','</flik>'), 
		'state' : self.getBetween(data, '<t>','</t>'), 
		'icon' : self.getBetween(data, '<icon>','</icon'),
		'pressure' : self.getBetween(data, '<r>','</r>'),
		'windspeed' : self.getBetween(wind, '<s>','</s>'), 
		'winddir' : self.getBetween(wind, '<t>','</t>'), 
		'humid' : self.getBetween(data, '<hmid>','</hmid>'),
		'vis' : self.getBetween(data, '<vis>','</vis>'),
		'dew' : self.getBetween(data, '<dewp>','</dewp>')
		}
		return tokenized		


	def getBetween(self, data, first, last):
		x = len(first)
		begin = data.find(first) +x
		end = data.find(last, begin)
		return data[begin:end]
	
	def get_icon(self, code):
		if code < 3200:
			weather = str(code)
		
		elif code == 3200:
			weather = "na"
		return weather

	

	def get_day_or_night(self, weather):
		time = weather[0]["time"].split()[0]
		ampm = weather[0]["time"].split()[1]
		sunset = weather[0]["suns"].split()[0]
		sunrise = weather[0]["sunr"].split()[0]

		hour = time.split(':')[0]
		min = time.split(':')[1]
		risehr = sunrise.split(':')[0]
		risemin = sunrise.split(':')[1]
		sethr = sunset.split(':')[0]
		setmin = sunset.split(':')[1]

		if int(hour) == 12:
			hour = 0
		if ampm == "AM" :
		        if int(risehr) > int(hour) :
		                dark = 1
		        elif int(risehr) < int(hour) :
				dark = 0
		        else :
		                if int(risemin) > int(min) :
        	                	dark = 1
      		          	elif int(risemin) < int(min) :
       	 	                	dark = 0
         		        else :
           				dark = -1

		elif ampm == "PM" :
		        if int(sethr) > int(hour) :
		                dark = 0
		        elif int(sethr) < int(hour) :
		                dark = 1
		        else :
		                if int(setmin) > int(min) :
		                        dark = 0
		                elif int(setmin) < int(min) :
		                        dark = 1
		                else :
		                        dark = -1
		if dark == 1:
			return "moon"
		else:
			return "sun"

## Screenlet Layout section ##

	def on_draw(self, ctx):
		weather = self.latest
		hourly = self.latestHourly
		# set size
		ctx.scale(self.scale * 3, self.scale * 3)
		
		# draw bg (if theme available)
		ctx.set_operator(cairo.OPERATOR_OVER)
		if self.theme:
			if (self.mini == False and weather != [] and self.custom_bg == False):
				self.theme['weather-bg.svg'].render_cairo(ctx)
			#elif (self.mini == True and self.custom_bg == False):
			elif (weather == [] and self.custom_bg == False):			
				self.theme['weather-bg-mini.svg'].render_cairo(ctx)
			elif (self.mini == False and self.custom_bg == True and weather != []):
		                ###Rounded Rectangle
		                ctx.save()
        		        ctx.translate(12, 18)  ##Correctly set to align with standard themes
		                ctx.scale(.33, .33)
				ctx.move_to(20, 0)
        		        ctx.line_to(341.5, 0)
        		        ctx.curve_to(351.5, 0, 361.5, 10, 361.5, 20)
        		        ctx.line_to(361.5, 221.5)
        		        ctx.curve_to(361.5, 231.5, 351.5, 241.5, 341.5, 241.5)
        		        ctx.line_to(20, 241.5)
        		        ctx.curve_to(10, 241.5, 0, 231.5, 0, 221.5)
        		        ctx.line_to(0, 20)
        		        ctx.curve_to(0 , 10, 10, 0, 20, 0)
        		        linear = cairo.LinearGradient(0.0, 0.0, 0, 241.5)
        		        linear.add_color_stop_rgba(0, self.bg_color1[0],  self.bg_color1[1],  self.bg_color1[2],  self.bg_color1[3])
        	   		linear.add_color_stop_rgba(1, self.bg_color2[0],  self.bg_color2[1],  self.bg_color2[2],  self.bg_color2[3])
        		        ctx.set_source(linear)
        		        ctx.fill_preserve()
        		        ctx.set_source_rgba(0, 0, 0, .5)
        		        ctx.stroke()
        		        ctx.restore()
        		         ###End of rounded rectangle
			
			elif (self.mini == True or weather == [] and self.custom_bg == True):
				ctx.save()
				#self.show_radar = False
				#self.theme['weather-bg-mini.svg'].render_cairo(ctx)
		                ctx.translate(12, 18)
				ctx.scale(.33, .33)
				ctx.move_to(20, 0)
        		        ctx.line_to(341.5, 0)
        		        ctx.curve_to(351.5, 0, 361.5, 10, 361.5, 20)
        		        ctx.line_to(361.5, 106.948)
        		        ctx.curve_to(361.5, 116.948, 351.5, 126.948, 341.5, 126.948)
        		        ctx.line_to(20, 126.948)
        		        ctx.curve_to(10, 126.948, 0, 116.948, 0, 106.948)
        		        ctx.line_to(0, 20)
        		        ctx.curve_to(0 , 10, 10, 0, 20, 0)
        		        linear = cairo.LinearGradient(0.0, 0.0, 0, 241.5)
        		        linear.add_color_stop_rgba(0, self.bg_color1[0],  self.bg_color1[1],  self.bg_color1[2],  self.bg_color1[3])
        		        linear.add_color_stop_rgba(1, self.bg_color2[0],  self.bg_color2[1],  self.bg_color2[2],  self.bg_color2[3])
        		        ctx.set_source(linear)
				#ctx.set_source_rgba(self.bg_color1[0],  self.bg_color1[1],  self.bg_color1[2],  self.bg_color1[3])
        		        ctx.fill_preserve()
        		        ctx.set_source_rgba(0, 0, 0, .5)
        		        ctx.stroke()
				ctx.restore()

			if (self.theme_name == "glassy"):
				ctx.set_source_rgba(0, 0, 0, 0.8)
			else:
				ctx.set_source_rgba(1, 1, 1, 0.8) ## Global font color for screenlet

			if weather == []:
				ctx.save()	
				ctx.translate(15, 35)
				if self.p_layout == None :
	
			                self.p_layout = ctx.create_layout()
		                else:
		
			                ctx.update_layout(self.p_layout)
				p_fdesc = pango.FontDescription()
				p_fdesc.set_family_static("Sans")
				p_fdesc.set_size(4 * pango.SCALE)
				p_fdesc.set_weight(300)
				p_fdesc.set_style(pango.STYLE_NORMAL)   ####render no info message
				self.p_layout.set_font_description(p_fdesc)
				self.p_layout.set_markup(_('<b>No weather information available</b>'))						
				ctx.show_layout(self.p_layout)
				ctx.restore()
			#else:
			elif self.show_radar == True and self.mini == False:
				
				img_file = weatherradar.get_map(self.ZIP)
				if img_file:       ####Waits until there is an image file before displaying
					#ctx.scale(self.scale / 3, self.scale / 3)  ###Removes distortion from image, but only at 100%
					ctx.translate(16.5, 21)
					ctx.scale(.34, .34) ##Fixes scaling issue and removes distortion from image
					radar_image = gtk.Image()
					radar_image.set_from_file(img_file)
					pixbuf = radar_image.get_pixbuf()
					scaled = pixbuf.scale_simple(int(325),int(219),gtk.gdk.INTERP_BILINEAR)
					surface = ctx.set_source_pixbuf(scaled,0,0)
			                ctx.scale(.90, .90) ##Scales new window slightly
					ctx.move_to(20, 0)
        			        ctx.line_to(341.5, 0)
        			        ctx.curve_to(351.5, 0, 361.5, 10, 361.5, 20)
	        		        ctx.line_to(361.5, 221.5)
        			        ctx.curve_to(361.5, 231.5, 351.5, 241.5, 341.5, 241.5)
        			        ctx.line_to(20, 241.5)
        			        ctx.curve_to(10, 241.5, 0, 231.5, 0, 221.5)
  		      		        ctx.line_to(0, 20)
        			        ctx.curve_to(0 , 10, 10, 0, 20, 0)
	
					ctx.fill_preserve()
					ctx.set_source_rgba(0, 0, 0, .5 )
					ctx.stroke()
				
				#print img_file  ##Used for debugging
			
			elif self.show_radar == False:		
				ctx.save()
				ctx.translate(0,0) ####Location of current weather icon on screenlet
				ctx.scale(.4,.4)  ####Scaled size of the current weather icon
				icon = str(self.get_icon(int(weather[0]["icon"])) )
				self.theme.render(ctx,icon)
				ctx.restore()
				
				ctx.save()
				ctx.translate(90,20)  ####Location of current temperature on screenlet
				degree = unichr(176)
				if self.p_layout == None :
	
			                self.p_layout = ctx.create_layout()
				else:
		
					ctx.update_layout(self.p_layout)
				p_fdesc = pango.FontDescription()
				p_fdesc.set_family_static("Sans")
				p_fdesc.set_size(14 * pango.SCALE)
				p_fdesc.set_weight(300)
				p_fdesc.set_style(pango.STYLE_NORMAL)
				self.p_layout.set_font_description(p_fdesc)   ######render current temp
				if len(str(weather[0]["temp"])) == 3:
					ctx.translate(-7, 0)
				if self.use_metric:
					unit = 'c'
				else:
					unit = 'f'
				self.p_layout.set_markup('<b>' + weather[0]["temp"] + '<span size="x-small"><sup>' + degree + unit + '</sup></span></b>')							
				ctx.show_layout(self.p_layout)
				ctx.restore()

				ctx.save()	
				ctx.translate(25  , 50)  ####Location of location name on screenlet ie.) New York
				if self.p_layout1 == None :
	
					self.p_layout = ctx.create_layout()
				else:
		
					ctx.update_layout(self.p_layout)
				p_fdesc = pango.FontDescription()
				p_fdesc.set_family_static("Sans")
				p_fdesc.set_size(6 * pango.SCALE)
			
			

				self.p_layout1.set_font_description(p_fdesc)      ### draw location

			
				self.p_layout1.set_width(int((102* pango.SCALE )))
				self.p_layout1.set_alignment(pango.ALIGN_RIGHT)
				self.p_layout1.set_markup('<b>' + weather[0]["where"][:weather[0]["where"].find(',')][:15] +'</b>')

				ctx.show_layout(self.p_layout1)
				ctx.restore()	

				if (self.mini == False):
					ctx.save() 
					ctx.translate(14, 60)  ####Location of the days of the week on screenlet
					self.theme['day-bg.svg'].render_cairo(ctx)   ###render the days background
					if self.p_layout == None :
	
						self.p_layout = ctx.create_layout()
					else:
		
						ctx.update_layout(self.p_layout)
					p_fdesc = pango.FontDescription()
					p_fdesc.set_family_static("Monospace")
					p_fdesc.set_size(6 * pango.SCALE)
					p_fdesc.set_weight(300)    ##### render the days of the week
					p_fdesc.set_style(pango.STYLE_NORMAL)
					self.p_layout.set_font_description(p_fdesc)
					self.p_layout.set_markup('<b>' +weather[1]["day"][:3] + '</b>')
					ctx.show_layout(self.p_layout)
					ctx.translate(20, 0)
					self.p_layout.set_markup('<b>' +weather[2]["day"][:3] + '</b>')	
					ctx.show_layout(self.p_layout)
					ctx.translate(20, 0)
					self.p_layout.set_markup('<b>' +weather[3]["day"][:3] + '</b>')	
					ctx.show_layout(self.p_layout)
					ctx.translate(20, 0)
					self.p_layout.set_markup('<b>' +weather[4]["day"][:3] + '</b>')	
					ctx.show_layout(self.p_layout)
					ctx.translate(20, 0)
					self.p_layout.set_markup('<b>' +weather[5]["day"][:3] + '</b>')
					ctx.show_layout(self.p_layout)
					ctx.translate(20, 0)
					self.p_layout.set_markup('<b>' +weather[6]["day"][:3] + '</b>')	
					ctx.show_layout(self.p_layout)
					ctx.restore()	

					ctx.save()
					ctx.translate(12, 73.5)  ####Location of weather indicator icons on bottom of screenlet
					ctx.scale(.17, .17)
					self.theme.render(ctx,self.get_icon(int(weather[1]["nighticon"]))  )
					ctx.restore()
					ctx.save()
					ctx.translate(32,73.5)
					ctx.scale(.17, .17)
					self.theme.render(ctx,   self.get_icon(int(weather[2]["dayicon"])) )	
					ctx.restore()
					ctx.save()
					ctx.translate(52,73.5)
					ctx.scale(.17, .17)
					self.theme.render(ctx,   self.get_icon(int(weather[3]["dayicon"]))  )	
					ctx.restore()
					ctx.save()
					ctx.translate(72,73.5)
					ctx.scale(.17, .17)
					self.theme.render(ctx,   self.get_icon(int(weather[4]["dayicon"]))  )	
					ctx.restore()
					ctx.save()
					ctx.translate(92,73.5)
					ctx.scale(.17, .17)
					self.theme.render(ctx,   self.get_icon(int(weather[5]["dayicon"]))  )	
					ctx.restore()
					ctx.save()
					ctx.translate(111,73.5)
					ctx.scale(.17, .17)
					self.theme.render(ctx,   self.get_icon(int(weather[6]["dayicon"]))  )	
					ctx.restore()						
					

					if self.p_layout == None :
	
						self.p_layout = ctx.create_layout()
					else:
		
						ctx.update_layout(self.p_layout)
					p_fdesc = pango.FontDescription()
					p_fdesc.set_family_static("Monospace")
					p_fdesc.set_size(int(3 * pango.SCALE))
					p_fdesc.set_weight(300)    ###note:: this font needs to be set only once for the next few 
					p_fdesc.set_style(pango.STYLE_NORMAL)  #things we need to do, so I'll do it here.
					self.p_layout.set_font_description(p_fdesc)	
		
					if self.show_daytemp == True:
						ctx.save()
						ctx.set_source_rgba(.1, .1, .1, 1)
						ctx.translate(14,69)  ####Location of first day temperature
						self.p_layout.set_markup('<b>' + weather[1]["high"]+degree+'</b>/' + weather[1]["low"]+degree)					
						ctx.show_layout(self.p_layout)   ##day1's temps
						ctx.restore()
		
						ctx.save()
						ctx.set_source_rgba(0, 0, 0, 1)
						ctx.translate(35, 69)
						self.p_layout.set_markup('<b>' + weather[2]["high"]+degree+'</b>/'+ weather[2]["low"]+degree)					
						ctx.show_layout(self.p_layout)
						ctx.restore()

						ctx.save()
						ctx.set_source_rgba(0, 0, 0, 1)
						ctx.translate(55, 69)
						self.p_layout.set_markup('<b>' + weather[3]["high"]+degree+'</b>/'+ weather[3]["low"]+degree)					
						ctx.show_layout(self.p_layout)
						ctx.restore()

						ctx.save()
						ctx.set_source_rgba(0, 0, 0, 1)
						ctx.translate(74, 69)
						self.p_layout.set_markup('<b>' + weather[4]["high"]+degree+'</b>/'+ weather[4]["low"]+degree)					
						ctx.show_layout(self.p_layout)
						ctx.restore()

						ctx.save()
						ctx.set_source_rgba(0, 0, 0, 1)
						ctx.translate(94, 69)
						self.p_layout.set_markup('<b>' + weather[5]["high"]+degree+'</b>/'+ weather[5]["low"]+degree)					
						ctx.show_layout(self.p_layout)
						ctx.restore()

						ctx.save()
						ctx.set_source_rgba(0, 0, 0, 1)
						ctx.translate(113, 69)
						self.p_layout.set_markup('<b>' + weather[6]["high"]+degree+'</b>/'+ weather[6]["low"]+degree)					
						ctx.show_layout(self.p_layout)
						ctx.restore()
				
			##elif self.mini == True and self.show_radar == True:
				### Might need to add elif statement for radar = true and mini = true
					##degree = unichr(176)
				if self.p_layout == None :
	
					self.p_layout = ctx.create_layout()
				else:
		
					ctx.update_layout(self.p_layout)
				p_fdesc = pango.FontDescription()
				p_fdesc.set_family_static("Sans")
				p_fdesc.set_size(3 * pango.SCALE)
				p_fdesc.set_weight(300)    ###note:: this font needs to be set only once for the next few 
				p_fdesc.set_style(pango.STYLE_NORMAL)  #things we need to do, so I'll do it here.
				self.p_layout2.set_font_description(p_fdesc)	
				ctx.translate(55, 23)  ####Location of current high temperature on screenlet
				self.p_layout2.set_markup('<b>_(High): ' + weather[1]["high"]+degree+'</b>')					
				ctx.show_layout(self.p_layout2)   ##displays day1's high temp
				ctx.translate(0, 5)  ####Location of current low temperature on screenlet
				self.p_layout2.set_markup('<b>_(Low): ' + weather[1]["low"]+degree+'</b>')
				ctx.show_layout(self.p_layout2)
				if self.show_precip == True:
					ctx.translate(0, 5)  ####Location of current days chance of precipitation on screenlet
					self.p_layout2.set_markup('<b>_(Precip): <i>' + weather[1]["dayppcp"] + '%</i></b>')
					ctx.show_layout(self.p_layout2)
				if self.show_wind == True:
					ctx.translate(0, 5)
					if weather[0]["winddir"] == _("CALM"):  ##Fixes issue with wind direction showing CALM when speed is calm
						weather[0]["winddir"] = ""
					self.p_layout2.set_markup('<b>_(Wind): <i>' + weather[0]["windspeed"] + ' ' + weather[0]["winddir"] + '</i></b>')
					ctx.show_layout(self.p_layout2)
				if self.show_visible == True:
					if self.use_metric == True:
						unit = "km"
					else:
						unit = "mi"	
					ctx.translate(0,5)
					self.p_layout2.set_markup('<b>_(Visible): <i>' + weather[0]["vis"] + ' ' + unit + '</i></b>')
					ctx.show_layout(self.p_layout2)
		
					


	def on_draw_shape(self,ctx):
		self.on_draw(ctx)

	def menuitem_callback(self, widget, id):
		screenlets.Screenlet.menuitem_callback(self, widget, id)
		if id=="zipcode":
			self.show_edit_dialog()
			self.update()
		if id == "mini" and self.show_radar == False:  ###Fixes issue where radar messes up mini mode
			self.mini = not self.mini
			self.update()
		if id == "use_metric":
			self.use_metric = not self.use_metric
			self.update()
		if id == "show_radar" and self.mini == False:  ###Fixes issue where radar messes up mini mode
			self.show_radar = not self.show_radar
			self.update()	


	def show_edit_dialog(self):
		# create dialog
		dialog = gtk.Dialog(_("Zip Code"), self.window)
		dialog.resize(300, 100)
		dialog.add_buttons(gtk.STOCK_OK, 1, gtk.STOCK_CANCEL, 2,)
		entrybox = gtk.Entry()
		entrybox.set_text(str(self.ZIP))
		dialog.vbox.add(entrybox)
		entrybox.set_activates_default(1)  ###Sets the default as active (boolean value)
		dialog.set_default_response(1)  ###Puts a blue indicator around OK, indicating default value
		entrybox.show()
		# run dialog
		response = dialog.run()
		if response == 1:
			self.ZIP = entrybox.get_text()
			self.updated_recently = 1
		elif response == 2:
			dialog.destroy()
		dialog.hide()
		self.update()





	def show_error(self):

		dialog = gtk.Dialog(_("Zip Code"), self.window)
		dialog.resize(300, 100)
		dialog.add_buttons(gtk.STOCK_OK, gtk.RESPONSE_OK)

		label = gtk.Label(_("Could not reach weather.com.  Check your internet connection and location and try again."))
		dialog.vbox.add(label)
		check = gtk.CheckButton(_("Do not show this again"))
		dialog.vbox.add(check)
		dialog.show_all()
		response = dialog.run()
		if response == gtk.RESPONSE_OK:
			if check.get_active() == True:
				self.show_error_message = 0			
			dialog.hide()


if __name__ == "__main__":
	import screenlets.session
	screenlets.session.create_session(SmoothWeatherScreenlet)
