import appuifw
import urllib
import e32
class App:
    def load_place(self, url):
        """This loads the format specified for the program, printing
        errors out if needed."""
        u = ""
        try:
            u = urllib.urlopen(url)
        except:
            appuifw.note(u"An error occured with that URL. Restarting...", "error")
            self.restart()
        try:
            title = unicode(u.readline()[:-1])
            urlpattern = u.readline()[:-1]
            tabs = u.readline()[:-1]
            places = dict()
            tab = dict()
            for i in tabs.split("\t"):
                l = i.split("::")
                places[l[1]] = dict()
                tab[l[1]] = unicode(l[0])
        except Exception, E:
            appuifw.note(u"This is not a valid file for this program. (%s)"%E, "error")
            self.restart()
            
        k = u.readline()[:-1]
        while k:
            try:
                i = k.split("\t")
                places[i[0]][i[1]] = unicode(i[2])
                appuifw.app.body.add(u".")
            except:
                appuifw.app.body.add(u"\nThe following line is ill formed: %s"%k)
            k = u.readline()[:-1]
        return (title, urlpattern, tab, places)
    def __init__(self):
        self.old_title = appuifw.app.title
        appuifw.app.title = u"Traffic Cams"
        appuifw.app.menu = [(u"Restart", self.restart)]
        appuifw.app.body = appuifw.Text(u"""Please wait a moment while the neccesary modules are loaded...""")
        self.lock = e32.Ao_lock()
        self.old_exit_key = appuifw.app.exit_key_handler
        appuifw.app.exit_key_handler = self.exit_handler
        self.listings = [
                        (u'London, UK', u'Contributed by JimH', 'http://crschmidt.oddones.org/london.dat'),
                        (u"Devon County, UK", u'Contributed by Alasdair Allan', 'http://crschmidt.oddones.org/devon.dat'),
                        (u"Dubai, UAE", u'Contributed by tarek', 'http://crschmidt.oddones.org/dubai.dat'),
                        (u"Arizona, US", u'Contributed by ', 'http://crschmidt.oddones.org/arizona.dat'),
                        (u"Columbus, US", u'Contributed by crschmidt', 'http://crschmidt.oddones.org/columbus.dat'),
                        (u"Houston, US", u'Contributed by kkhan', 'http://crschmidt.oddones.org/houston.dat'),
                        (u'New York, US', u'Contributed by crschmidt', 'http://crschmidt.oddones.org/newyork.dat'), 
                        (u"San Antonio, US", u'Contributed by kkhan', 'http://crschmidt.oddones.org/sanantonio.dat'),
                        (u"San Francisco, US", u'Contributed by miker', 'http://crschmidt.oddones.org/sanfrancisco.dat'),
                        (u"Seattle, US", u'Contributed by ErikT', 'http://mobile.thauvin.net/traffic/seattle'),
                        (u"Sydney, AU", u'Contributed by Dean Maslic', 'http://crschmidt.oddones.org/sydney.dat'),
                        (u"Italy", u'Contributed by luca', 'http://crschmidt.oddones.org/italy.dat'),
                        (u"New Zealand", u'Contributed by Pokoka', 'http://crschmidt.oddones.org/newzealand.dat'),
                        (u"Other...", u"", "")
                        ]
        self.popuplist = []
        for i in self.listings:
            self.popuplist.append(i[0])
        self.restart()
        self.lock.wait()
    def load_data(self, url):
        data = self.load_place(url)
        appuifw.app.title = data[0]
        self.url = data[1]
        self.maps_list = []
        tabs_list = []
        for i in data[2].keys():
            self.maps_list.append(data[3][i])
            tabs_list.append(data[2][i])
        self.current_tab = 0
        appuifw.app.set_tabs(tabs_list, self.display_tab)
        self.display_tab(0)
    def exit_handler(self):
        appuifw.app.set_tabs([],None)
        appuifw.app.title = self.old_title
        appuifw.app.exit_key_handler = self.old_exit_key
        self.lock.signal()
    def display_tab(self, id):
        appuifw.app.body = appuifw.Listbox(self.maps_list[id].values(), self.load)
        self.current_tab = id
    def restart(self):
        appuifw.app.body = appuifw.Text(u"""Please wait a moment while the city data is loaded...""")
        try:
            option = appuifw.popup_menu(self.popuplist, u'Choose a set of Images...')
            if option != None:
                if self.listings[option][2]:
                    appuifw.app.body.add(u"""\n\nPlease wait a moment while we load the URLs for the selected city...\n""")
                    self.load_data(self.listings[option][2])
                else:
                    url = appuifw.query(u"Enter your own URL.", "text", u"http://")
                    if url:
                        self.load_data(url)
                    else:
                        appuifw.note(u"You didn't enter a URL. Restarting...", "info")
                        self.restart()
            else:
                self.exit_handler()
        except Exception, E:
            appuifw.note(u"Error: %s"%E, "error")
    def load(self):
        try:
            id = appuifw.app.body.current()
            k = self.maps_list[self.current_tab].keys()
            url = self.url%k[id]
            appuifw.note(u"Loading image...", "info")
            urllib.urlretrieve(url, "C:\\Traffic Image.jpg")
            content_handler = appuifw.Content_handler()
            content_handler.open("C:\\Traffic Image.jpg")
        except IOError:
            appuifw.note(u"Could not fetch the image.",'info')
        except Exception, E:
            appuifw.note(u"Could not open the data, %s"%E,'info')
A = App()

