#!/usr/bin/env python2.5
# Maemo Plazes handler (C) 2007 Henri Bergius and Eero af Heurlin
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

"""maemoplazer: a Plazes geopositioning client"""

# PLEASE DO NOT CHANGE FORMAT OF __version__ LINE (setup.py reads this)

__author__    = "Henri Bergius <henri.bergius@iki.fi>"
__version__   = "1.0.0"
__date__      = "2007-02-11"
__copyright__ = "Copyright (c) 2007 %s. All rights reserved." % __author__
__licence__   = "GPL"

import osso
import dbus
from pyplazer import PyPlazer

class MaemoPlazer(PyPlazer):
    def __init__(self, configfile, osso_sysnote):
        self.osso_sysnote = osso_sysnote
        PyPlazer.__init__(self, configfile)
        
    def uiMessage(self, message):
        self.osso_sysnote.system_note_infoprint(message)

    def updateAccount(self):
        import gtk
        import hildon
    
        window = hildon.Window()
        window.set_title("Maemo Plazer")
    
        dialog = hildon.NamePasswordDialog(window)
        
        window.show_all()
        
        response = dialog.run()
        dialog.hide()
        
        if response == gtk.RESPONSE_OK:
            self.config.set("account", "username", dialog.get_name())
            self.config.set("account", "password", dialog.get_password())
            dialog.destroy()
            window.destroy()
            
            file = open(self.configfile, 'w')
            self.config.write(file)
            
            return True
        else:
            dialog.destroy()
            return False

def run():    
    import os

    # Register OSSO DBUS context
    osso_c = osso.Context("maemoplazer", "1.0.0", False)
    osso_sysnote = osso.SystemNote(osso_c)

    configfile = os.path.expanduser('~/.maemoplazes.cfg')
    
    # Instantiate the Plazer
    plazer = MaemoPlazer(configfile, osso_sysnote)
    location = plazer.getLocationID()

    # Start a new session
    session = plazer.login(location)
    if (session == False):
        return 1
        
    status = plazer.update(session, location)
    # Critical failure
    if (status == False):
        return 1

    # Sanity check our response data
    while (True):
        try:
            test = status["update"]
            test = status["editurl"]
            break
        except KeyError:
            # We're missing some critical keys, reget
            status = plazer.update(session, location)

    # Check if we're in a new Plaze
    if (status["update"] == 2):
        # This is a new plaze
        plazer.uiMessage("Plazes: You have discovered a new Plaze.")

        # Launch browser DBUS service
        bus = dbus.SessionBus()
        proxy_obj = bus.get_object('com.nokia.osso_browser', '/com/nokia/osso_browser')
        dbus_iface = dbus.Interface(proxy_obj, 'com.nokia.osso_browser')
        # Make browser use correct url
        dbus_iface.open_new_window(str(status["editurl"]))
        return 0

    # Get info on the Plaze we're in
    info = plazer.plazeinfo(session, location)
    if (status == False):
        return 1
        
    if (info["name"] == ""):
        # Plazes API burped, try again
        info = plazer.plazeinfo(session, location)
        if (info == False):
            return 1
            
        if (info["name"] == ""):
            plazer.uiMessage("Plazes: Failed to retrieve information about your location.")
            return 1

    # Send system note on the Plaze
    plazer.uiMessage("Plazes: You're in %s (%s, %s)." % (info["name"],  info["city"], info["country"]))

if __name__ == "__main__":
    # If we're used as a program, just connect and open Maemo Browser once
    # we have a response from Plazes.
    import sys
    sys.exit(run())
