#!/usr/bin/env python
# -*- coding: UTF-8 -*-
###
#
# Dynamic wallpaper is the legal property of Philip Andonov
# Copyright (c) 2007 Philip Andonov
# Based on weather-wallpaper by Raul Gonzalez Duque
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation
#
# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
###

import string
import ConfigParser
import gettext
import gtk
import os
import pygtk
import pymetar
import sys
import threading
import time
import urllib2
import math
#import pdb
#from svg import SVGFile
#from svg.effects import overlay
#from svg.color import color_to_grayscale,darken
import motor



__version__ = "0.3.1"

class pos:
	def __init__(self):
		self.lng=0
		self.lat=0

class suntimes:    
	def __init__(self):
		self.lat = 0#42.68333
		self.lng = 0#-23.31667
		self.dtime = 2  
		self.m_dtime = 0      
		self.ampm = 1
		self.dst = 0      
		self.r_to_d = 180 / math.pi      
		self.d_to_r = 1 / self.r_to_d      
		self.convday = 4.16666666666667E-02      
		self.convhour = 6.66666666666667E-02      
		self.convmin = 1.66666666666667E-02      
		self.convsec = 2.77777777777778E-04      
		self.convcircle = 2.77777777777778E-03      
		self.SUNSET = -.833333333333333      
		self.CIVIL = -6.0      
		self.NAUTICAL = -12.0      
		self.ASTRONOMICAL = -18.0      
		self.maxDay = 30
		self.rise=0
		self.transit=0
		self.set=0
     
	def radians(self,x):
		return x * self.d_to_r      

	def degrees(self,x):
		return x * self.r_to_d      

	def myatan2(self,y,x): 
		a=0      
		if x ==0:
			x=1e-30
		else:
			x=x
		a = self.degrees(math.atan(y/x))
		if(x < 0):
			a = 180 + a
		if(a < 0):
			a = 360 + a
		return a
 
	def mdy_jd(self,mo,da,yr,hh,mm,ss): # was struct datim q      
		a=0
		b=0
		jd=0      
		if(mo < 3):
			yr -= 1
			mo += 12
			a = da + (mo * 100) + (yr * 10000)
		if (a < 15821015.0): ## Julian calendar */      
			b = 0
		else: ## Gregorian */      
			a = math.floor(yr/100)
			b = 2 - a + math.floor(a/4)
		jd = math.floor(365.25*(yr+4716.0)) + math.floor(30.6001*(mo+1)) + da + b - 1524.5
		jd += (hh/24) + (mm/1440) + (ss/86400)
		return(jd)

	def calcsun(self,xjd,hh,mm,ss): # compute sun's position on this date         
		h=0
		s=pos
		jd=0    
		t=0      
		lo =0     
		m =0     
		rm=0      
		e =0     
		c =0     
		tl =0     
		v =0     
		r =0     
		nut =0     
		al =0     
		obliq  =0    
		sunra =0     
		sundecl =0     
		jd = xjd-(self.dtime/24) # convert to GMT */      
		h = ((hh) + (mm/60) + (ss/3600)) * 15      
		t = (jd - 2451545) * 2.7378507871321E-05      
		lo = 280.46645 + (36000.76983 * t) + (0.0003032 * t * t)      
		m = 357.5291 + (35999.0503 * t) - (0.0001559 * t * t) - (0.00000048 * t * t * t)      
		rm = self.radians(m)      
		e = 0.016708617 - (0.000042037 * t) - (0.0000001236 * t * t)      
		c = (1.9146 - 0.004817 * t - 0.000014 * t * t) *math.sin(rm)      
		c = c + (0.019993 - 0.000101 * t) * math.sin(2 * rm)      
		c = c + 0.00029 * math.sin(3 * rm)      
		tl = lo + c      
		v = m + c      
		r = (1.000001018 * (1 - e * e)) / (1 + (e * math.cos(self.radians(v))))      
		nut = 125.04 - 1934.136 * t      
		al = self.radians(tl - 0.00569 - 0.00478 * math.sin(self.radians(nut)))      
		obliq = 23.4391666666667 - 1.30041666666666E-02 * t - 0.000000163888888 * t * t + 5.03611111111E-08 * t * t * t      
		obliq = self.radians(obliq + 0.00256 * math.cos(self.radians(nut)))      
		sunra = self.myatan2(math.cos(obliq) * math.sin(al),math.cos(al))      
		if (sunra < 0):      
			sunra = 360 + sunra      
		sundecl = self.degrees(math.asin(math.sin(obliq) * math.sin(al)))      
		s.lat = sundecl      
		s.lng = sunra      
		return(s)      

#=================================           
# sidereal time from Julian Date */      
	def sidtime(self,jd,lng):      
		t=0
		x=0      
		t = ((math.floor(jd) + 0.5) - 2451545) *2.73785078713210E-05      
 	      
		x = 280.46061837      
		x = x + 360.98564736629 * (jd - 2451545)      
       
		x = x + 0.000387933 * t * t      
		x = x - (t * t * t) * 2.583311805734950E-08      
		x = x - lng      
		x = x * self.convcircle      
		x = x - math.floor(x)      
		x = x * 360      
		return(x)      

	def mod1(self,t):      
		ot = t
		t = math.fabs(t)
		t = t - math.floor(t)
		if(ot < 0):      
			t = 1-t
		return(t)

	def rmstime(self,jd,lat,lng,timezone,atcr,ra,decl): 
		x=0
		gmtsid=0
		timezone *= self.convday      
		gmtsid = self.sidtime(math.floor(jd) + 0.5, 0)      
		transit = ((ra + lng - gmtsid) / 360)      
		atcr = self.radians(atcr)      
		lat = self.radians(lat)      
		decl = self.radians(decl)      
		x = math.sin(atcr) - (math.sin(lat) * math.sin(decl))      
		x = x / (math.cos(lat) * math.cos(decl))      
		if ((x < 1) and (x > -1)):      
			x = self.degrees(math.acos(x)) * self.convcircle      
			rise = (self.mod1((transit - x)+timezone)) * 24.0      
			set = (self.mod1((transit + x)+timezone)) * 24.0      
			transit = (self.mod1(transit+timezone)) * 24.0      
		else:     
			if x>=0:
				x=-100
			else:
				x=100
			rise = x      
			transit = x      
			set = x      
		return (rise, transit, set)      

	def fix_places(self,x):
		x = "" + str(x)      
		if(len(x) < 2):
			x = "0" + str(x)      
		return x      

	def dd_dm(self,x,f):
		d=0
		m=0
		sgn=0      
		r=0
		if x>=0:
			sgn=0
		else:
			x=1
		x = math.abs(x)+.008333      
		d = math.floor(x)      
		x = (x-d) * 60      
		m = math.floor(x)      
		d = fix_places(d)      
		m = fix_places(m)      
		if(f == 0):
			r = d       
		if(f == 1):
			r = m      
		if(f == 2):
			r = sgn      
		return r      

	def dt_hms(self,x,amdsp,dst):
		h=0
		m=0
		s=0
		ampm=""
		outstr=""
		if((x > -100) and (x < 100)):
			if x<0:
				x=0
			h = math.floor(x)      
			x = (x-h) * 60      
			h = (h+dst) % 24 # daylight time adjustment      
			m = math.floor(x)      
			x = (x-m) * 60      
			s = math.floor(x)      
			#if(amdsp > 0):
			#	if h>11:
			#		ampm=" PM"
			#	else:
			#		ampm=" AM"
			#	h = h % 12      
			#	if h<1:
			#		h=12
			#else:
			#	ampm = ""      
#=================
			#h = self.fix_places(int(h))      
			#m = self.fix_places(int(m))      
			#s = self.fix_places(int(s))      
			#outstr = h + ":" + m + ":" + s# + ampm      
		#else:
		#	if x<0:
		#		outstr="[Below]"
		#	else:
		#		outstr="[Above]"
		#return outstr      
		return int(h),int(m)

def moon_phase(month, day, year):
    ages = [18, 0, 11, 22, 3, 14, 25, 6, 17, 28, 9, 20, 1, 12, 23, 4, 15, 26, 7]
    offsets = [-1, 1, 0, 1, 2, 3, 4, 5, 7, 7, 9, 9]
    description = ["new",
      "waxcres",
      "fq",
      "waxgib",
      "full",
      "wangib",
      "lq",
      "wancres"]
    months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    
    if day == 31:
        day = 1
    days_into_phase = ((ages[(year + 1) % 19] + ((day + offsets[month-1]) % 30) + (year < 1900)) % 30)
    index = int((days_into_phase + 2) * 16/59.0)
    if index > 7:
        index = 7
    status = description[index]    
     # light should be 100% 15 days into phase
    light = int(2 * days_into_phase * 100/29)
    if light > 100:
        light = abs(light - 200);
    date = "%d%s%d" % (day, months[month-1], year)
    
    return date, status, light

def season(month):
	if month>=3 and month<6:
		return "spring"
	if month>=6 and month<9:
		return "summer"
	if month>=9 and month<12:
		return "autumn"
	if (month>=1 and month<3) or month==12:
		return "winter"
	#return "spring"
	

class PreferencesDialog(gtk.Dialog):
    """Dialog box which displays the preferences."""
    def __init__(self):
        gtk.Dialog.__init__(self)
        self.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
        self.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
        self.set_title(_("Preferences"))
        self.set_size_request(400, 400)
        self.connect("response", self.on_dialog_response)

        vbox = gtk.VBox()

        # Location section
        title = gtk.Label()
        title.set_markup("<span size=\"large\" weight=\"bold\">" + _("Location") + "</span>")
        hbox = gtk.HBox()
        hbox.pack_start(title, expand=False, fill=True, padding=2)
        vbox.pack_start(hbox, expand=False, fill=True, padding=0)

        help = gtk.Label()
        help.set_markup("<span size=\"small\">" + _("ICAO Location Indicator for your city which can be found at") + "</span>")
        help.set_line_wrap(True)
        hbox = gtk.HBox()
        hbox.pack_start(help, expand=False, fill=False, padding=5)
        vbox.pack_start(hbox, expand=False, fill=False, padding=0)
        url = gtk.LinkButton("http://www.nws.noaa.gov/tg/siteloc.shtml", _("NOAA webpage"))
        url.connect("clicked", self.open_web) 
        hbox = gtk.HBox()
        hbox.pack_start(url, expand=False, fill=False, padding=0)
        vbox.pack_start(hbox, expand=False, fill=False, padding=0)

        lbl_location = gtk.Label(_("ICAO: "))
        self.entry_location = gtk.Entry()
        self.entry_location.set_text(station_id)
        hbox = gtk.HBox()
        hbox.pack_start(lbl_location, expand=False, fill=False, padding=5)
        hbox.pack_start(self.entry_location, expand=False, fill=False, padding=0)
        vbox.pack_start(hbox)


        # Units section
        title = gtk.Label()
        title.set_markup("<span size=\"large\" weight=\"bold\">" + _("Units") + "</span>")
        hbox = gtk.HBox()
        hbox.pack_start(title, expand=False, fill=False, padding=2)
        vbox.pack_start(hbox, expand=False, fill=False, padding=0)

        help = gtk.Label()
        help.set_markup("<span size=\"small\">" + _("System of units you want to use. With Metric, units will be displayed using °C and Km; with Imperial, °F and Mi.") + "</span>")
        help.set_line_wrap(True)
        hbox = gtk.HBox()
        hbox.pack_start(help, expand=False, fill=False, padding=5)
        vbox.pack_start(hbox, expand=False, fill=False, padding=0)

        self.metric = gtk.RadioButton(group=None, label="Metric")
        self.metric.set_active(unit_system == "metric")
        self.imperial = gtk.RadioButton(group=self.metric, label="Imperial")
        self.imperial.set_active(unit_system == "imperial")
        hbox = gtk.HBox()
        hbox.pack_start(self.metric, expand=False, fill=False, padding=5)
        hbox.pack_start(self.imperial, expand=False, fill=False, padding=0)
        vbox.pack_start(hbox, expand=False, fill=False, padding=0)

        hbox = gtk.HBox()
        vbox.pack_start(hbox, expand=True, fill=True, padding=0)


        # Offset
        title = gtk.Label()
        title.set_markup("<span size=\"large\" weight=\"bold\">" + _("Offset") + "</span>")
        hbox = gtk.HBox()
        hbox.pack_start(title, expand=False, fill=False, padding=2)
        vbox.pack_start(hbox, expand=False, fill=False, padding=0)

        help = gtk.Label()
        help.set_markup("<span size=\"small\">" + _("With this setting you can change the position of the letters on the screen. A positive number will move the text to the right (x) or bottom (y). A negative one, to the left (x) or top (y).") + "</span>")
        help.set_line_wrap(True)
        hbox = gtk.HBox()
        hbox.pack_start(help, expand=False, fill=False, padding=5)
        vbox.pack_start(hbox, expand=False, fill=False, padding=0)

        lbl_offset_x = gtk.Label(_("Offset x: "))
        self.entry_offset_x = gtk.Entry()
        self.entry_offset_x.set_text(str(offset_x))
        hbox = gtk.HBox()
        hbox.pack_start(lbl_offset_x, expand=False, fill=False, padding=5)
        hbox.pack_start(self.entry_offset_x, expand=False, fill=False, padding=0)
        vbox.pack_start(hbox)

        lbl_offset_y = gtk.Label(_("Offset y: "))
        self.entry_offset_y = gtk.Entry()
        self.entry_offset_y.set_text(str(offset_y))
        hbox = gtk.HBox()
        hbox.pack_start(lbl_offset_y, expand=False, fill=False, padding=5)
        hbox.pack_start(self.entry_offset_y, expand=False, fill=False, padding=0)
        vbox.pack_start(hbox)


        # Proxy
        title = gtk.Label()
        title.set_markup("<span size=\"large\" weight=\"bold\">" + _("Proxy") + "</span>")
        hbox = gtk.HBox()
        hbox.pack_start(title, expand=False, fill=False, padding=2)
        vbox.pack_start(hbox, expand=False, fill=False, padding=0)

        help = gtk.Label()
        help.set_markup("<span size=\"small\">" + _("If you connect to the Internet using a proxy specify it here.") + "</span>")
        help.set_line_wrap(True)
        hbox = gtk.HBox()
        hbox.pack_start(help, expand=False, fill=False, padding=5)
        vbox.pack_start(hbox, expand=False, fill=False, padding=0)

        lbl_proxy = gtk.Label(_("Proxy: "))
        self.entry_proxy = gtk.Entry()
        self.entry_proxy.set_text(http_proxy)
        hbox = gtk.HBox()
        hbox.pack_start(lbl_proxy, expand=False, fill=False, padding=5)
        hbox.pack_start(self.entry_proxy, expand=False, fill=False, padding=0)
        vbox.pack_start(hbox)


        hbox = gtk.HBox()
        vbox.pack_start(hbox, expand=True, fill=True, padding=0)

        # Theme
        title = gtk.Label()
        title.set_markup("<span size=\"large\" weight=\"bold\">" + _("Theme") + "</span>")
        hbox = gtk.HBox()
        hbox.pack_start(title, expand=False, fill=False, padding=2)
        vbox.pack_start(hbox, expand=False, fill=False, padding=0)

        help = gtk.Label()
        help.set_markup("<span size=\"small\">" + _("Write the name of the theme you want to use here") + "</span>")
        help.set_line_wrap(True)
        hbox = gtk.HBox()
        hbox.pack_start(help, expand=False, fill=False, padding=5)
        vbox.pack_start(hbox, expand=False, fill=False, padding=0)

        lbl_theme = gtk.Label(_("Theme: "))
        self.entry_theme = gtk.combo_box_new_text()
        for t in os.listdir(os.path.join(path,"images")):
        	if os.path.isdir(os.path.join(path,"images",t)):
        		self.entry_theme.append_text(t)
        hbox = gtk.HBox()
        hbox.pack_start(lbl_theme, expand=False, fill=False, padding=5)
        hbox.pack_start(self.entry_theme, expand=False, fill=False, padding=0)
        vbox.pack_start(hbox)


        hbox = gtk.HBox()
        vbox.pack_start(hbox, expand=True, fill=True, padding=0)

        # Scrolled window
        scrolled_window = gtk.ScrolledWindow()
        scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scrolled_window.add_with_viewport(vbox)
        self.vbox.pack_start(scrolled_window, expand=True, fill=True, padding=0)
        self.show_all()
        self.run()
        self.destroy()
        
    def get_active_text(self,combobox):
        model = combobox.get_model()
        active = combobox.get_active()
        if active < 0:
            return None
        return model[active][0]
      
    def open_web(self, widget):
        """Called when the user clicks on the link button. Opens NOAA webpage."""
        import webbrowser
        webbrowser.open_new(widget.get_uri())

    def on_dialog_response(self, widget, response):
        """When the user closes the dialog by selecting OK, update the preferences."""
        if response == gtk.RESPONSE_OK:
            global station_id, unit_system, http_proxy, http_theme, offset_x, offset_y
            # Get the new values
            new_location = self.entry_location.get_text()
            if self.metric.get_active():
                new_unit = "metric"
            else:
                new_unit = "imperial"
            new_proxy = self.entry_proxy.get_text()
            new_theme = self.get_active_text(self.entry_theme)
           # new_theme = self.entry_theme.get_text()
            try:
                new_offset_x = float(self.entry_offset_x.get_text())
            except:
                new_offset_x = offset_x
            try:
                new_offset_y = float(self.entry_offset_y.get_text())
            except:
                new_offset_y = offset_y

            # If the user changed something update the conf file and the vars
            # and wake up the updater
            if (new_location != station_id or new_unit != unit_system or 
                new_proxy != http_proxy or new_offset_x != offset_x or
                new_offset_y != offset_y or new_theme != http_theme):
                cfg.set("General", "station id", new_location)
                cfg.set("General", "unit system", new_unit)
                cfg.set("General", "proxy", new_proxy)
                cfg.set("General", "theme", new_theme)
                cfg.set("General", "offset_x", str(new_offset_x))
                cfg.set("General", "offset_y", str(new_offset_y))
                cfg.write(open(os.path.expanduser("~") + "/.dynamic-wallpaper/conf", "w"))
                station_id = new_location
                unit_system = new_unit
                http_proxy = new_proxy
                http_theme = new_theme
                offset_x = new_offset_x
                offset_y = new_offset_y
                self.destroy()
                updater.stop_event.set()




class MyAboutDialog(gtk.AboutDialog):
    def __init__(self):
        super(MyAboutDialog, self).__init__()

        self.set_name("Dynamic wallpaper")
        self.set_comments("Wallpaper with the current weather and more")
        self.set_version(__version__)
        self.set_copyright("Copyright © 2007 Philip Andonov")
        self.set_license(file(os.path.join(path, "COPYING"), "r").read())
        self.set_website("fpages.info")
        self.set_website_label("fpages")
        self.set_authors([file(os.path.join(path, "AUTHORS"), "r").read()])
        self.set_translator_credits(file(os.path.join(path, "TRANSLATORS"), "r").read())
        self.set_artists(["Icons by the Tango Desktop Project", "Fog icons by Pepetps"])

        self.set_logo(gtk.gdk.pixbuf_new_from_file(os.path.join(path, "images", "snow.svg")))

        self.set_modal(True)
        self.show_all()
        self.run()
        self.destroy()


class Updater(threading.Thread):
    """Thread which updates the status icon and the wallpaper every hour"""
    def __init__(self):
        """Constructor, to set the initial values for the variables"""
        self.stop_event = threading.Event()
        self.stop = False
        threading.Thread.__init__(self)

    def run(self):
        
        """Execution loop for the thread. Creates and sets a new wallpaper with the info downloaded from NOAA"""
        while not self.stop:
            self.stop_event = threading.Event()
            #statusIcon.set_from_stock(gtk.STOCK_REFRESH)
            #statusIcon.set_tooltip(_("Retrieving report"))

            # The station ID can be found here: http://www.nws.noaa.gov/tg/siteloc.shtml
            fetcher = pymetar.ReportFetcher(station_id)
            parser = pymetar.ReportParser()
            try:
                report = fetcher.FetchReport(proxy=http_proxy)
            except (urllib2.URLError, pymetar.NetworkException):
                #statusIcon.set_tooltip(_("There is a network problem. Trying again in 1 minute."))
                print _("There is a network problem. Trying again in 1 minute.")
                # Wait until the timeout elapses (1 minute) or until the stop
                # event is set by another thread
                self.stop_event.wait(60)
                self.run()
                return
            report = parser.ParseReport(report)
           # pdb.set_trace()
            cloud_info=parser.extractCloudInformation()
            print "Cloud information:",cloud_info
            print "Sky conditions:",report.getSkyConditions()
                        #"Few clouds" "Clear sky"
            #clouds=report.getWeather()
            if cloud_info!=None:
            	clouds_list=cloud_info[0].split(" ")
            	clouds=clouds_list[0].lower()
            else:
            	clouds="clear"
            if clouds=="clear":
				clouds=""
            #clear, Few, Scattered, Broken, Overcast
            print "Short weather:",report.getWeather()
            #print "Full report:", report.getFullReport()

            if not report.valid:
                print _("The downloaded report is not valid")
                exit()
            image=""
            image = report.pixmap
            #image="sun"
            print "WEATHER IMAGE",image
            now=time.localtime()
            ye, mo, day, hour, minute=now[0:5]
            date, status, light = moon_phase(mo,day,ye)
            print "HOUR:",hour
            print "MINUTE:",minute
            #print "getStationPositionFloat():",report.getStationPositionFloat()
            latsign=1
            lngsign=1
            if report.getStationLatitude()[-1]=="S":
            	latsign=-1
            if report.getStationLongitude()[-1]=="E":
            	lngsign=-1
            ss=suntimes()
            ss.lng=report.getStationLongitudeFloat()*lngsign
            ss.lat=report.getStationLatitudeFloat()*latsign
            print "ss.lng",ss.lng            
            print "ss.lat",ss.lat            
            gmt=time.gmtime()
            dtime=now[3]-gmt[3]
            s = pos
            ye=ye-1900
            jd = ss.mdy_jd(mo,day,ye,0,0,0)
            s = ss.calcsun(jd,0,0,0)
            r = ss.rmstime(jd,ss.lat,ss.lng,dtime,ss.SUNSET,s.lng,s.lat)
            sunrisetime=ss.dt_hms(r[0],ss.ampm,ss.dst)
            print "Sunrise:",sunrisetime
            transittime=ss.dt_hms(r[1],ss.ampm,ss.dst)
            print "Transit:",transittime
            sunsettime=ss.dt_hms(r[2],ss.ampm,ss.dst)
            print "Sunset:",sunsettime
            dayonly=nightonly=""

            if (hour>sunrisetime[0] and hour<sunsettime[0]) or (hour == sunsettime[0] and minute <= sunsettime[1]) or (hour == sunrisetime[0] and minute >= sunrisetime[1]):
            	img="sun"
            	daynight="day"
            else:
            	daynight="night"
            	img="moon"		
            	if image!=None:
            		image=image.replace("sun","moon")
            	if image=="fog":
            		image="moonfog"
            	print "ARGH:",image
            	            
            # Before sunrise
            if hour == sunrisetime[0]-1 and minute>=sunrisetime[1]:
                foreground = "#1E5073"
                backgroundcolor = "#1E5073"

            # Sunrise
            if hour == sunrisetime[0] and  minute>=sunrisetime[1]:
                foreground = "#666666"
                backgroundcolor = "#6E98AE"

            # Before afternoon
            if hour > sunrisetime[0] and hour < transittime[0]:
                foreground = "#6E98AE"
                backgroundcolor = "#97BFCB"

            # Afternoon
            if hour >=transittime[0] and hour < sunsettime[0]:
                foreground = "#6382b9"
                backgroundcolor = "#8fb6ff"

            # Twilight
            if  hour >= sunsettime[0] and  hour < sunsettime[0]+2:
                foreground = "#333333"
                backgroundcolor = "#694174"

            # Night
            if hour >= sunsettime[0]+2 or hour < sunrisetime[0]-1:
                foreground = "#33436a"
                backgroundcolor = "#000000"

            #if it is cloudy, then background is gray
            #if image=="rain" or image=="snow" or image=="storm":
            	#foreground=color_to_grayscale(foreground)
            	#backgroundcolor=color_to_grayscale(backgroundcolor)
            #theme="sad_tree"
            #"city_skyline"
            background = motor.ObjectStack(False)
            #SVGFile(os.path.join(path, "images",http_theme, "sky.svg"))
            luminary=weather1=extra=weather2=""
            #svg_list=[]
            #print "BACKGROUND:"+os.path.join(path, "images",http_theme, clouds+".svg")#"sky.svg")
            #a = background.add_linear_gradient("my_gradient", startx=0, starty=960, stopx=0, stopy=0)
            print "Adding gradient stops"
            #a.add_stop(color=backgroundcolor, offset="0")
            #a.add_stop(color=foreground, offset="1")
            print "Backgroundcolor:",backgroundcolor
            print "foreground",foreground
            #a.__setattr__("x1",0)
            #a.__setattr__("y1",height)
            #a.__setattr__("x2",0)
            #a.__setattr__("y2",0)
            #a.__setattr__("gradientUnits","userSpaceOnUse")
            #background.add_rect(x="0", y="0", width="1280", height="960", fill="url(#my_gradient)",stroke="#0000BBff", stroke_width="0", roundedx="0", roundedy="0")
            #background.add_rect(x="0", y="0", width=width, height=height, fill="url(#my_gradient)",stroke="#0000BBff", stroke_width="0", roundedx="0", roundedy="0")

            if image=="cloud":
            	pngimage=img+image
            else:
            	pngimage=image
            original_file = os.path.join(path, "images", "%s.png" % pngimage)
            print "original file:",original_file
           # if not os.path.exists(original_file):
            #    image = "None"

            if unit_system.lower() == "metric":
                temperature_num = report.getTemperatureCelsius()
                visibility_num = report.getVisibilityKilometers()
                dewpoint_num = report.getDewPointCelsius()
                wind_speed_num = report.getWindSpeed()

                if not temperature_num:
                    temperature = ""
                else:
                    temperature = "%d°C" % temperature_num

                if not visibility_num:
                    visibility = ""
                else:
                    visibility = "%.2fKm" % visibility_num

                if not dewpoint_num:
                    dewpoint = ""
                else:
                    dewpoint = "%d°C" % dewpoint_num

                if not wind_speed_num:
                    wind_speed = ""
                else:
                    wind_speed = "%.2fm/s" % wind_speed_num
            else:
                temperature_num = report.getTemperatureFahrenheit()
                visibility_num = report.getVisibilityMiles()
                dewpoint_num = report.getDewPointFahrenheit()
                wind_speed_num = report.getWindSpeed() * 2.237

                if not temperature_num:
                    temperature = ""
                else:
                    temperature = "%d°F" % temperature_num

                if not visibility_num:
                    visibility = ""
                else:
                    visibility = "%.2fMi" % visibility_num

                if not dewpoint_num:
                    dewpoint = ""
                else:
                    dewpoint = "%d°F" % dewpoint_num

                if not wind_speed_num:
                    wind_speed = ""
                else:
                    wind_speed = "%.2fmph" % wind_speed_num


            humidity_num = report.getHumidity()
            if not humidity_num:
                humidity = ""
            else:
                humidity = ("%d" % humidity_num) + "%"

            pressure_num = report.getPressure()
            if not pressure_num:
                pressure = ""
            else:
                pressure = "%.2fhPa" % pressure_num

            if not wind_speed:
                wind = ""
            else:
                wind = wind_dirs[str(report.getWindCompass())] + _(" at ") + wind_speed

#==========================================================================
            if image!="rain" and image!="snow" and image!="storm":
            	if img == "moon":
            		luminary=status+img
            	else:
            		luminary=img
            	print "luminary:",luminary
            	print "STATUS:",status
            	print "IMG:",img
            	if status=="new" and img=="moon":
            		luminary=""
            if image=="suncloud" or image=="mooncloud":
            	image="cloud"
            if image=="moonfog":
            	image="fog"            	
            if image!="sun" and image!="moon" and image!=None:
            	weather1=image
            print "weather1:",weather1
            extra=""
            if mo==10 and day==31:
	            extra="halloween"
            if mo==12 and day==25:
	            extra="xmas"	            
            if image=="snow":
            	weather1="snow5"
            	weather2="snow4"
            print "Extra layer:",extra
            f = open(os.path.join(path,"images",http_theme,'layers.txt'))
            svg_string_list=f.read()
            f.close()
            svg_string_list=svg_string_list.strip('\n')
            svg_string_list=svg_string_list.replace("$luminary",luminary)
            if weather1 == "cloud":
            	svg_string_list=svg_string_list.replace("$weather1","")
            else:
            	svg_string_list=svg_string_list.replace("$weather1",weather1)
            svg_string_list=svg_string_list.replace("$season",season(now[1]))
            svg_string_list=svg_string_list.replace("$extra",extra)
            svg_string_list=svg_string_list.replace("$daynight",daynight)            
            svg_string_list=svg_string_list.replace("$weather2",weather2)
            svg_string_list=svg_string_list.replace("$sky",clouds)
            #svg_string_list=svg_string_list.replace("cloud",clouds)
            svg_list=svg_string_list.split(",")
            print "svg_list:",svg_list
            for svgimg in svg_list:
            	if svgimg!="":
            		if daynight=="night" and svgimg=="nightshade":
            			kur=1#layer_svg.add_rect(x="0", y="0", width=width, height=height, fill="#00000088")
            		else:
            			if svgimg!="nightshade": 
            				layer_svg = os.path.join(path, "images",http_theme,svgimg+".svg")
            		#overlay(background,layer_svg)
            		background.addFeature(layer_svg)
#if svgimg.startswith("night_only")
#==========================================================================
            xx = width -200 + offset_x
            yy = height - (height * 0.2) + offset_y

            report_str = report.getStationCity() + "\n"
            from time import strftime
            report_str += str(strftime("%a, %d %b %Y %H:%M")) + "\n\n"
            #text = background.add_text(x=xx, y=yy+20, text=report_str, fill="#000000ff")
            #text = background.add_text(x=xx+1, y=yy+21, text=report_str, fill="#AAAAAAff")
            
            if temperature:
                report_str = _("Temperature: ") + "%s\n" % (temperature)
                #text = background.add_text(x=xx, y=yy+40, text=report_str, fill="#000000ff")
                #text = background.add_text(x=xx+1, y=yy+41, text=report_str, fill="#AAAAAAff")                
            if humidity:
                report_str = _("Humidity: ") + "%s\n" % (humidity)
                #text = background.add_text(x=xx, y=yy+60, text=report_str, fill="#000000ff")
                #text = background.add_text(x=xx+1, y=yy+61, text=report_str, fill="#AAAAAAff")                
            if visibility:
                report_str = _("Visibility: ") + "%s\n" % (visibility)
                #text = background.add_text(x=xx, y=yy+80, text=report_str, fill="#000000ff")
                #text = background.add_text(x=xx+1, y=yy+81, text=report_str, fill="#AAAAAAff")                
            if dewpoint:
                report_str = _("Dew point: ") + "%s\n" % (dewpoint)
                #text = background.add_text(x=xx, y=yy+100, text=report_str, fill="#000000ff")
                #text = background.add_text(x=xx+1, y=yy+101, text=report_str, fill="#AAAAAAff")                
            if wind:
                report_str = _("Wind: ") + "%s\n" % (wind)
                #text = background.add_text(x=xx, y=yy+120, text=report_str, fill="#000000ff")
                #text = background.add_text(x=xx+1, y=yy+121, text=report_str, fill="#AAAAAAff")                
            if pressure:
                report_str = _("Pressure: ") + "%s\n" % (pressure)
                #text = background.add_text(x=xx, y=yy+140, text=report_str, fill="#000000ff")
                #text = background.add_text(x=xx+1, y=yy+141, text=report_str, fill="#AAAAAAff")

            print "XXX:",xx
            print "YYY:",yy
            #background.__setattr__("width",800)
            background.writeToFile(output_img)
            print "Background saved in "+output_img

            # If the user is running Gnome
            if os.popen( "ps --user " + os.environ.get( "USER" ) + "| grep gnome-panel").readline():
                import gconf
                client = gconf.client_get_default()
                client.set_string("/desktop/gnome/background/picture_filename", output_img)
                client.set_string("/desktop/gnome/background/picture_options", "centered")

                client.set_string("/desktop/gnome/background/color_shading_type", "vertical-gradient")
                client.set_string("/desktop/gnome/background/primary_color", foreground)
                client.set_string("/desktop/gnome/background/secondary_color", backgroundcolor)
            # If the user is running KDE
            elif os.popen( "ps --user " + os.environ.get( "USER" ) + "| grep kdesktop" ).readline():
                cmd = "dcop kdesktop KBackgroundIface setWallpaper \"%s\" 1 " % (output_img)
                os.popen(cmd)
                cmd = "dcop kdesktop KBackgroundIface setColor \"%s\" false" % (backgroundcolor)
                os.popen(cmd)
                cmd = "dcop kdesktop KBackgroundIface setColor \"%s\" true" % (foreground)

            statusIcon.set_from_file(original_file)
            print "ICON:",original_file
            #statusIcon.set_tooltip(_(temperature))
            #statusIcon.set_tooltip("%s (%s)" % (report.getStationCity(), temperature))

            # Wait until the timeout elapses (30 minutes) or until the stop event
            # is set by another thread
            self.stop_event.wait(1800)


def quit(widget, data=None):
    """Exists the gtk main loop and sets the stop event for the updater thread
    to stop"""
    gtk.main_quit()
    updater.stop = True
    updater.stop_event.set()


def popup_menu(widget, button, time, data=None):
    """Called whenever the user clicks on the status icon"""
    if button == 3:
        if data:
            data.show_all()
            data.popup(None, None, None, 3, time)
    pass


def show_about(widget, data=None):
    """Shows the about dialog"""
    about = MyAboutDialog()


def show_preferences(widget, data=None):
    preferences = PreferencesDialog()


def refresh(widget):
    updater.stop_event.set()



gettext.install("dynamic-wallpaper")


screen = gtk.gdk.display_get_default().get_default_screen()
screen_size = screen.get_monitor_geometry(0)
width = screen_size.width
height = screen_size.height


default_location = "LEGT"
default_units = "metric"

wind_dirs = {"N":_("North"), "S":_("South"), "E":_("East"), "W":_("West"),
        "NE":_("Northwest"), "NW":_("Northeast"), "SE":_("Southeast"),
        "SW":_("Southwest"), "NNE":_("North Northeast"),
        "NNW":_("North Northwest"), "SSE":_("South Southeast"),
        "SSW":_("South Southwest"), "ENE":_("East Northeast"),
        "ESE":_("East Southeast"), "WNW":_("West Northwest"),
        "WSW":_("West Southwest"), "None":_("None")}

output_img = os.path.expanduser("~") + "/.dynamic-wallpaper/.wallpaper.svg"

path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "..", "share",
                       "dynamic-wallpaper"))

# Read the configuration values from the config file. If the file does not exist
# create it with the default values
cfg = ConfigParser.SafeConfigParser()

if not os.path.exists(os.path.expanduser("~") + "/.dynamic-wallpaper/"):
    os.mkdir(os.path.expanduser("~") + "/.dynamic-wallpaper/")

if not os.path.exists(os.path.expanduser("~") + "/.dynamic-wallpaper/conf"):
    cfg.add_section("General")
    cfg.set("General", "station id", default_location)
    cfg.set("General", "unit system", default_units)
    cfg.set("General", "proxy", "")
    cfg.set("General", "offset_x", "0")
    cfg.set("General", "offset_y", "0")
    cfg.write(open(os.path.expanduser("~") + "/.dynamic-wallpaper/conf", "w"))

cfg.readfp(file(os.path.expanduser("~") + "/.dynamic-wallpaper/conf"))

try:
    station_id = cfg.get("General", "station id")
except:
    station_id = default_location

try:
    unit_system = cfg.get("General", "unit system")
except:
    unit_system = default_units

try:
    http_proxy = cfg.get("General", "proxy")
except:
    http_proxy = ""

try:
    http_theme = cfg.get("General", "theme")
except:
    http_theme = "sad_tree"

try:
    offset_x = float(cfg.get("General", "offset_x"))
except:
    offset_x = 0.0

try:
    offset_y = float(cfg.get("General", "offset_y"))
except:
    offset_y = 0.0


try:

    # Create the status icon
    statusIcon = gtk.StatusIcon()
    statusIcon.set_from_stock(gtk.STOCK_REFRESH)
    menu = gtk.Menu()

    # Run the thread which updates the wallpaper
    updater = Updater()
    updater.start()


    menuItem = gtk.ImageMenuItem(gtk.STOCK_REFRESH)
    menuItem.connect("activate", refresh)
    menu.append(menuItem)

    sep = gtk.SeparatorMenuItem()
    menu.append(sep)

    menuItem = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
    menuItem.connect("activate", show_preferences)
    menu.append(menuItem)

    menuItem = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
    menuItem.connect("activate", show_about)
    menu.append(menuItem)

    sep = gtk.SeparatorMenuItem()
    menu.append(sep)

    menuItem = gtk.ImageMenuItem(gtk.STOCK_QUIT)
    menuItem.connect("activate", quit, statusIcon)
    menu.append(menuItem)

    statusIcon.connect("activate", show_preferences)
    statusIcon.set_visible(True)
    statusIcon.connect("popup-menu", popup_menu, menu)


    gtk.gdk.threads_init()
    gtk.main()
except (KeyboardInterrupt, SystemExit):
    updater.stop = True
    updater.stop_event.set()



