#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Weather Gnome Wallpaper Thing 0.1
# 
# Copyright (c) 2009, Jonas Häggqvist
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
# * Neither the name of the program nor the names of its contributors may be
#   used to endorse or promote products derived from this software without
#   specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# 
# Requirements:
# - pymetar
# - nodebox-web

import sys
try:
    import pymetar
    from nodebox_web.web import flickr
except ImportError:
    print("""Error: required modules not found

$ sagi python-pymetar python-nodebox-web
""")
    sys.exit()

def getweather(station):
    print("Get weather for %s" % station)
    # This is just crazy... pemetar - you are demented!
    report = pymetar.ReportParser().ParseReport(
            pymetar.ReportFetcher(station).FetchReport()
    )
    return report

def getsearchwords(weather):
    words = []

    # Try to guess a bit depending on temperature
    # Perhaps it would be wise to use the latitude for this
    # (25 doesn't mean summer in Arizona)
    if weather.getTemperatureCelsius() > 25.0:
        words.append("summer")
    elif weather.getTemperatureCelsius() < -5.0:
        words.append("winter")
    
    try:
        words.extend(
                {
                    "sun" : ("sun", "sunny"),
                    "suncloud" : ("sun", "clouds"),
                    "cloud" : ("cloudy", "overcast"),
                }[weather.getPixmap()]
        )
    except KeyError:
        pass

    return words

def getimage(words):
    print "Search flickr for %s" % ", ".join(words)
    search = flickr.search(" ".join(words), start=1, count=10, wait=10,
            cached=True, sort="interest")
    search.sort() # Do I need to sort here?
    image = search[0]
    image.download(size="wallpaper")
    return image.path
    
def setwallpaper(path):
    import gconf
    client = gconf.client_get_default ()
    client.set_string ("/desktop/gnome/background/picture_filename", path)

if __name__ == "__main__":
    weather = getweather(sys.argv[1])
    searchwords = getsearchwords(weather)
    path = getimage(searchwords)
    setwallpaper(path)
