#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2005,2007 by İsmail Dönmez <ismail@pardus.org.tr>
# Licensed under GPL v2 or later at your option

import sys
from subprocess import *

port = sys.argv[1]
server = sys.argv[2]
target = sys.argv[3]

msg_template = "Current weather for %%B%s%%B : Temperature: %%B%s%%B, Pressure: %%B%s%%B, Wind: %%B%s%%B"
msg_detailed_template = "Current weather for %%B%s%%B : %%B%s%%B, Temperature: %%B%s%%B, Pressure: %%B%s%%B, Wind: %%B%s%%B"

def printMessage(message=None):
    Popen(['dcop', port, 'default', 'say', server, target, message]).communicate()

def printError(message=None):
    Popen(['dcop', port, 'default', 'error', message]).communicate()

def getData(section, station=None):
    if station:
        data = Popen(['dcop','KWeatherService','WeatherService', section, station], stdout=PIPE).communicate()[0].rstrip("\n")
    else:
        data = Popen(['dcop','KWeatherService','WeatherService', section], stdout=PIPE).communicate()[0].rstrip("\n")
        
    return data

def stationMessage(station):
     city = getData("stationName", station)
     temperature = getData("temperature", station)
     pressure = getData("pressure", station)
     wind = getData("wind", station)
     detail = getData("weather", station)
     detail2 = getData("cover", station)

     if detail2:
         if detail:
             detail = detail+', '+detail2
         else:
             detail = detail2

     if detail:
         return msg_detailed_template % (city,detail,temperature,pressure,wind)
     else:
         return msg_template % (city,temperature,pressure,wind)

def printWeather(index):
    stations = getData("listStations").split("\n")

    if index != None:
        if index <= 0:
            printError("Station index should be bigger than zero!")
        elif index > len(stations):
            printError("Station index is out of range")
        else:
            printMessage(stationMessage(stations[index-1]))
    else:
        for station in stations:
            printMessage(stationMessage(station))
    
if __name__ == "__main__":
    try:
        index = int(sys.argv[4])
    except IndexError:
        index = None

    printWeather(index)
