# !Currency.py.Update/py

import swi
import wimp
import ConvrtW
import Rates


def update():
    global window_update
    window_update = wimp.window('update')
    status(wimp.lookup('status.begin'), 1, wimp.lookup('action.begin'))
    window_update.open_centred(-1)
    window_update.put_caret()
    if action():
        return
    while 1:
        status(wimp.lookup('status.updating'), 0, 0)
        wimp.hourglass_on()
        try:
            Rates.update(wimp.lookup('url'), '<Currency$Dir>.Rates',
                         wimp.lookup('us'), wimp.lookup('dollar'))
        except IOError, (type, error):
            wimp.hourglass_off()
            swi.swi(0x107, '')
            status(wimp.lookup('status.error') % (type, error), 1, wimp.lookup('action.error'))
            if action():
                return
            continue
        break
    ConvrtW.update()
    wimp.hourglass_off()
    status(wimp.lookup('status.done') % Rates.date(), 0, wimp.lookup('action.done'))
    if action():
        return
    window_update.remove()


def action():
    while 1:
        event, details = wimp.poll(1)
        if event == 6:
            if details[0] == window_update:
                window_update.put_caret()
            if details[0] == window_update and details[1] == 2:
                return 0
            elif details[0] == window_update and details[1] == 1:
                window_update.remove()
                return 1
            elif details[0] != window_update:
                window_update.remove()
                wimp.handle((event, details))
                return 1
        elif event == 8:
            if details[0] == window_update and details[2] == 0xd:
                return 0
            elif details[0] == window_update and details[2] == 0x1b:
                window_update.remove()
                return 1
            else:
                wimp.handle((event, details))
        else:
            wimp.handle((event, details))


def status(status, cancel, action):
    window_update.icon_text(0, status)
    window_update.icon_grey(1, 1 - cancel)
    if action == 0:
        window_update.icon_grey(2)
    else:
        window_update.icon_ungrey(2)
        window_update.icon_text(2, action)
