#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009 HDE, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#

import snack
import traceback
import sys
import os
import re
import time

import installer.uninstall
from installer.trans import _, N_
from installer.const import *

class SnackUI(object):

    def __init__(self, opts):

        self.opts = opts
        self.screen = snack.SnackScreen()

        self.size   = snack._snack.size()
        self.width  = min(self.size[0]-10,100)
        self.height = self.size[1]-15

        self.wins = [
                     WelcomeWin,
                     ConfirmWin,
                     FinishWin,
                    ]

    def run(self):
        self.screen.drawRootText(0, 0, "Goodbye to %s %s" % (TITLE,VERSION,))
        self.screen.drawRootText(self.size[0]-len(COPYRIGHT), 0, "%s" % (COPYRIGHT))

        page = 0
        while page < len(self.wins):
            func = self.wins[page](self.screen, self, self.opts)
            ret = func()

            if ret in [OK_VALUE, YES_VALUE, F12_VALUE]:
                page = page + 1
            elif ret == BACK_VALUE:
                page = page - 1
            elif ret in [CANCEL_VALUE, NO_VALUE, EXIT_VALUE]:
                page = page + 1
                break

        self.cleanup()

        if page >= len(self.wins):
            if ret in [OK_VALUE, YES_VALUE, F12_VALUE]:
                print _("Done.")
        else:
            installer.uninstall.write_log(_("Aborted page [%s].") % self.wins[page-1].__name__)
            print _("Aborted.")

        installer.uninstall.write_log(_("Finish time: %s") % time.ctime())
        print _("See '%s' for detail.") % self.opts.logfile

        return ret

    def cleanup(self):
        if self.screen:
            self.screen.finish()

    def __del__(self):
        self.cleanup()

class ProgressWin:
    def __init__(self, screen, width):
        self.screen = screen
        self.width = width
        self.scale = snack.Scale(int(width), 100)

    def pop(self):
        self.screen.popWindow()
        self.screen.refresh()
        del self.scale
        self.scale = None

    def set(self, amount):
        self.scale.set(amount)
        self.screen.refresh()

    def update(self, amount):
        self.set(amount)

    def end(self, amount):
        self.update(amount)

    def start(self, size=None, now=None, text=None):

        if size is None:
            size = 1

        width = 55
        if (len(text) > width):
            width = min(len(text), self.width)

        self.text = snack.TextboxReflowed(width, text)

        self.screen.refresh()
        g = snack.GridForm(self.screen, _("Progress"), 1, 2)
        g.add(self.text, 0, 0, (0, 0, 0, 1), anchorLeft=1)

        self.scale = snack.Scale(width, size)
        g.add(self.scale, 0, 1)

        g.draw()
        self.screen.refresh()

def progressWin(screen, width):
    return ProgressWin(screen, width)

class BaseWin:
    def __init__(self, screen, ui, opts):
        self.ui = ui
        self.opts = opts
        self.screen = screen
        size = snack._snack.size()

class WelcomeWin(BaseWin):
    def __init__(self, *kwargs):
        BaseWin.__init__(self, *kwargs)
        self.opts.rpmsdir = getattr(self.opts, 'rpmsdir', "")

    def __precheck__(self):

        from installer.utils import is_installed
        if is_installed("karesansui") is False:
            raise installer.uninstall.UninstallError(_("Karesansui has not been installed yet."))

    def __call__(self):

        try:
            self.__precheck__()
        except installer.uninstall.UninstallError, e:
            installer.uninstall.write_log(e)
            r = snack.ButtonChoiceWindow(self.screen,_("ERROR"), e.value,
                    [EXIT_BUTTON], self.ui.width)
            return EXIT_VALUE

        text = snack.TextboxReflowed(self.ui.width,
                 _("Welcome to Karesansui Uninstallation Program."))

        buttons = snack.ButtonBar(self.screen, [OK_BUTTON, CANCEL_BUTTON], compact=BUTTON_COMPACT)

        g = snack.GridFormHelp(self.screen, _("Welcome"), None, 1, 2)
        g.add(text, 0, 0, padding = (0, 0, 0, 1))
        g.add(buttons, 0, 1, growx = 1)

        button = buttons.buttonPressed(g.runOnce())

        if button is None:
            button = OK_VALUE

        if button in [OK_VALUE]:
            dargs = {}
            dargs["progress_callback"] = progressWin(self.screen, self.ui.width)

            try:
                self.opts = installer.uninstall.pre_run(self.opts, **dargs)
                ret = OK_VALUE
            except installer.uninstall.UninstallError, e:
                error_msg = _("An error occurred while setting up the uninstaller.\n%s" % e.value)
                installer.uninstall.write_log(error_msg)
                r = snack.ButtonChoiceWindow(self.screen,_("ERROR"), error_msg,
                        [EXIT_BUTTON], self.ui.width)
                ret = EXIT_VALUE

        return ret

class ConfirmWin(BaseWin):
    def __init__(self, *kwargs):
        BaseWin.__init__(self, *kwargs)

    def __call__(self):

        confirm_msg = _("Are you sure to proceed to uninstall?")
        try:
            confirm_msg += "\n\n" + _("Uninstalled packages are:\n%s") % ",".join(self.opts.packages)
            installer.uninstall.write_log(confirm_msg)
        except:
            pass

        ret = snack.ButtonChoiceWindow(self.screen, _("Confirm"), confirm_msg,
                [OK_BUTTON, BACK_BUTTON, CANCEL_BUTTON], self.ui.width)

        if ret is None:
            ret = OK_VALUE

        if ret in [OK_VALUE, F12_VALUE]:

            dargs = {}
            dargs["progress_callback"] = progressWin(self.screen, self.ui.width)

            #import pdb; pdb.set_trace()
            try:
                installer.uninstall.run(self.opts, **dargs)
                ret = OK_VALUE
            except installer.uninstall.UninstallError, e:
                error_msg = _("An error occurred while setting up the uninstaller.\n%s" % e.value)
                installer.uninstall.write_log(error_msg)
                r = snack.ButtonChoiceWindow(self.screen,_("ERROR"), error_msg,
                        [EXIT_BUTTON], self.ui.width)
                ret = EXIT_VALUE

        return ret


class FinishWin(BaseWin):
    def __init__(self, *kwargs):
        BaseWin.__init__(self, *kwargs)

    def __call__(self):

        confirm_msg = _("Uninstallation was finished. Bye!!")

        return snack.ButtonChoiceWindow(self.screen,_("Finish"), confirm_msg,
                [YES_BUTTON, NO_BUTTON], self.ui.width)

