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

import os
import sys
import re
from subprocess import *

if __name__ == "__main__":

    port = sys.argv[1]
    server = sys.argv[2]
    target = sys.argv[3]
    
    try:
        option = int(sys.argv[4])
    except IndexError:
        pass

    stations = os.popen('dcop KWeatherService WeatherService listStations').readlines()

    if not stations:
        os.popen('dcop %s default error KWeather is not installed or not running!'%(port))

    try:
        if option and stations[option-1]:
            stations = stations[option-1]
    except NameError:
        pass

    for station in stations:

        city = os.popen('dcop KWeatherService WeatherService stationName %s'%(station)).readline().rstrip('\n')
        temperature = os.popen('dcop KWeatherService WeatherService temperature %s'%(station)).readline().rstrip('\n')
        pressure = os.popen('dcop KWeatherService WeatherService pressure %s'%(station)).readline() .rstrip('\n')
        wind = os.popen('dcop KWeatherService WeatherService wind %s'%(station)).readline().rstrip('\n')
        detail = os.popen('dcop KWeatherService WeatherService weather %s'%(station)).readline().rstrip('\n')
        detail2 = os.popen('dcop KWeatherService WeatherService cover %s'%(station)).readline().rstrip('\n')

        detail = ', '.join(re.split('\n',detail))
        detail2 = ', '.join(re.split('\n',detail2))

        if detail2:
            if detail:
                detail = detail+', '+detail2
            else:
                detail = detail2
        else:
            pass
      
        if detail:
            message = 'Current weather for %%B%s%%B : %%B%s%%B, Temperature: %%B%s%%B, Pressure: %%B%s%%B, Wind: %%B%s%%B'%(city,detail,temperature,pressure,wind)
        else:
            message = 'Current weather for %s : Temperature: %%B%s%%B, Pressure: %%B%s%%B, Wind: %%B%s%%B'%(city,temperature,pressure,wind)

        Popen(['dcop', port, 'default', 'say', server, target, message]).communicate()
