# !NewsStats.py.MainW/py

import os
import string
import swi
import time
import types
import wimp
import Analyse
import Iconbar
import Newsbase

temps = []
group = None
analysing = 0


class main_window(wimp.window):
    
    def __init__(self):
        wimp.window.__init__(self, 'main')

    def click(self, icon, buttons = 0, x = 0, y = 0, sx = 0, sy = 0):
        "Mouse click in main window"
        global temps
        if icon == 1:
            group_menu()
        elif icon == 2:
            self.close()
        elif icon == 3 and not group is None:
            temp = '<Wimp$ScrapDir>.NewsStats.' + hex(int(time.time()))[2:]
            temps.append(temp)
            if analyse(group, temp):
                if group == 0:
                    swi.swi(0x400de, 's', 'Filer_OpenDir ' + temp)
                else:
                    swi.swi(0x400de, 's', 'Filer_Run ' + temp + '.index/html')
        elif icon == 4 and not group is None:
            window_save.path(group_dir(group))
            window_save.open_centred(-1)

    def key(self, icon, key):
        "Key pressed in main window"
        # enter
        if key == 0xd:
            self.click(3)
        # ctrl-f2 / esc
        elif key == 0x1a2 or key == 0x1b:
            self.close()
        # pass on other interesting keys
        elif key > 0xff:
            # Wimp_ProcessKey
            swi.swi(0x400dc, 'i', key)


def init():
    global w, window_status, window_save
    w = main_window()
    window_status = wimp.window('status')
    window_save = wimp.save_window(save, 0x1000)


def group_menu():
    global group, groups
    login = Newsbase.SetUser(w.icon_text(8), w.icon_text(10))
    if login:
        wimp.warning(login)
        return
    groups = Newsbase.ListGroups(w.icon_text(8))
    if isinstance(groups, types.StringType):
        wimp.warning(groups)
        return
    menu_popup = wimp.menu('groups', ['groups', 'all'] + groups)
    reopen = 1
    while reopen:
        selection, reopen = menu_popup.popup(w, 1)
        if not selection is None:
            if selection[0] == 0:
                group = 0
                w.icon_text(0, wimp.m['all'])
            else:
                group = groups[selection[0] - 1]
                w.icon_text(0, group)
            w.icon_ungrey(3)
            w.icon_ungrey(4)


def set_status(group = '', message = '', of = ''):
    window_status.icon_text(0, group)
    window_status.icon_text(1, message)
    window_status.icon_text(2, of)


def group_dir(group):
    if group == 0:
        return wimp.m['dir']
    else:
        return string.replace(group, '.', '-')


def save(path, unsafe):
    if unsafe:
        return 0
    window_save.close()
    analyse(group, path)


def analyse(group, path):
    global analysing
    analysing = 1
    fast = not w.icon_set(7)
    ok = 1
    set_status()
    window_status.open_centred(-1)
    w.close()
    wimp.handle(wimp.poll(0))
    if group == 0:
        for group in groups:
            result = Analyse.group(group, os.path.join(path, group_dir(group)), fast)
            if result == 0:
                pass
            elif isinstance(result, types.StringType):
                wimp.warning(result)
    else:
        result = Analyse.group(group, path, fast)
        if result == 0:
            wimp.warning(wimp.m['warning.noarticles'])
            ok = 0
        elif isinstance(result, types.StringType):
            wimp.warning(result)
            ok = 0
    window_status.close()
    analysing = 0
    return ok
