# Copyright (c) 2000-2001 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# 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.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

"""Preferences View"""

__revision__ = "$Id: PrefView.py,v 1.17 2002/01/17 18:41:21 zoe Exp $"

from DialogWindow import DialogWindow,unicode_to_gtk
from PrefModel import PrefModel
from PrefController import PrefController
from gtk import *

class PrefView(DialogWindow):
    """
    View of preferences is a dialog window
    using singleton pattern
    """

    _DICT_ = {}

    def __init__(self):
        self.__dict__ = self._DICT_

        if not self.__dict__ :
            DialogWindow.__init__(self,unicode_to_gtk(_("Preferences")))
            self.connect("delete_event",self._hide)
            self.notebook = GtkNotebook()
            self.append_dialog(self.notebook)
            self.ok_button.show()
            self.ok_button.set_flags(CAN_DEFAULT|HAS_DEFAULT)
            self.ok_button.connect('clicked',self._hide,'ok')
            self.apply_button.show()
            self.apply_button.children()[0].set_text(unicode_to_gtk(_("Save")))
            self.apply_button.connect("clicked",lambda x:PrefController().save_preferences())
            self.cancel_button.show()
            self.cancel_button.connect("clicked",self._hide,'cancel')
            pmodel = PrefModel()
            pmodel.attach_observer(self)
            for label in pmodel.keys():
                widget, label = self._build_part(label)
                if widget:
                    self.notebook.append_page(widget, GtkLabel(label))
#            self.plan_button.set_active(pmodel.monitoring['destroy'])
            self.notebook.show_all()
            
    def update_sample(self, model):
        style = model.current_style['gtkstyle']
        self.sample.set_style(style)
        listchild = self.sample.children()
        for j in range(len(listchild)):
            listchild[j].set_style(style)
        self.sample.show()
            
    ## Listeners ##############################################################
    def PrefModel_update(self, observable,changes):
        print "changes", changes
        for change in changes:
            if change[0] == 'destroy':
                self.plan_button.set_active(change[1])
            elif change[0] == 'sample':
                self.update_sample(observable)
            elif change[0] == 'init':
                for label in observable.prefs.keys():
                    widget, label = self._build_part(label)
                    if widget:
                        widget.show_all()
                        self.notebook.append_page(widget,GtkLabel(label))
            else:
                self.update_sample(observable)
        self.notebook.show_all()

    ## Private ################################################################
    def _hide(self, *args):
        if args[-1]!='cancel':
            PrefModel().notify_observers()
        self.hide()

    def _build_part(self, label):
        if label == 'recipe':
            return self._recipe_display(),unicode_to_gtk(_('Recipe display style'))
        elif label == 'messages':
            return self._message_display(),unicode_to_gtk(_('Colors of messages'))
        elif label == 'monitoring':
            return self._monitor_display(),unicode_to_gtk(_('Monitor plan'))
        print 'build part error'
        return None

    def _message_display(self):
        vbox = GtkHButtonBox()
        vbox.set_layout_default(BUTTONBOX_SPREAD)
        popped_button = GtkButton(unicode_to_gtk(_('Popped color...')))
        popped_button.connect("clicked",PrefController().choose_color, 'popped-color')
        vbox.pack_start(popped_button,expand=FALSE)
        pushed_button = GtkButton(unicode_to_gtk(_('Posted color...')))
        pushed_button.connect("clicked",PrefController().choose_color, 'pushed-color')
        vbox.pack_start(pushed_button,expand=FALSE)
        return vbox

    def _monitor_display(self):
        self.plan_button = GtkCheckButton(
            unicode_to_gtk(_("Destroy window when monitored plan is done ?")))
        self.plan_button.connect("clicked",PrefController().destroy_plan, 'destroy')
        return self.plan_button

    def _recipe_display(self):
        # first create a hbox
        hbox = GtkHBox()

        maxsizeentry = GtkEntry()
        maxsizeentry.set_usize(30,25)
        maxsizeentry.set_text(
        str(PrefModel()._prefs['recipe']['max-display-char']))


        table = GtkTable(7,2)
        table.set_row_spacings(5)
        table.set_col_spacings(5)
        
        table.attach(GtkLabel(unicode_to_gtk(_('Element : '))),0,1,0,1,0,0)
        table.attach(GtkLabel(unicode_to_gtk(_('State : '))),0,1,1,2,0,0)
        table.attach(GtkLabel(unicode_to_gtk(_('Max display chars :'))),0,1,2,3,0,0)
        pcontrol = PrefController()
        # widget creation
        et_ddlist = GtkOptionMenu()
        et_ddlist.set_usize(100,25)
        table.attach(et_ddlist,1,2,0,1,EXPAND|FILL,0)
        st_ddlist = GtkOptionMenu()
        st_ddlist.set_usize(100,25)
        table.attach(st_ddlist,1,2,1,2,EXPAND|FILL,0)

        maxsizeentry.connect('focus-out-event',pcontrol.maxchars_changed, maxsizeentry)
        table.attach(maxsizeentry, 1,2,2,3,EXPAND|FILL,0)
        
        fn_button = GtkButton(unicode_to_gtk(_('Font...')))
        fn_button.set_usize(80,25)
        fn_button.connect('clicked',pcontrol.choose_font,'font')
        table.attach(fn_button,0,2,3,4,EXPAND|FILL,0,5)
        fc_button = GtkButton(unicode_to_gtk(_('Font color...')))
        fc_button.set_usize(80,25)
        fc_button.connect('clicked',pcontrol.choose_color,'font-color')
        table.attach(fc_button,0,2,4,5,EXPAND|FILL,0,5)
        bc_button = GtkButton(unicode_to_gtk(_('Border color...')))
        bc_button.set_usize(80,25)
        bc_button.connect('clicked',pcontrol.choose_color,'border-color')
        table.attach(bc_button,0,2,5,6,EXPAND|FILL,0,5)
        bg_button = GtkButton(unicode_to_gtk(_('Background...')))
        bg_button.set_usize(80,25)
        bg_button.connect('clicked',pcontrol.choose_color,'background')
        table.attach(bg_button,0,2,6,7,EXPAND|FILL,0,5)
        

        # state step menu
        state_step_menu = GtkMenu()
        for item in PrefModel().steps_style.keys():
            menu_item = GtkMenuItem(item)
            menu_item.set_data("state",item)
            menu_item.connect('activate',pcontrol.state_selection_changed)
            state_step_menu.append(menu_item)

        # state transition menu
        state_transition_menu = GtkMenu()
        for item in PrefModel().trans_style.keys():
            menu_item = GtkMenuItem(item)
            menu_item.set_data("state",item)
            menu_item.connect('activate',pcontrol.state_selection_changed)
            state_transition_menu.append(menu_item)

        type_menu = GtkMenu()
        menu_item = GtkMenuItem("step")
        menu_item.set_data("type","step")
        menu_item.connect("activate",pcontrol.type_selection_changed,
                          state_step_menu,state_transition_menu,st_ddlist)
        type_menu.append(menu_item)        
        menu_item = GtkMenuItem("transition")
        menu_item.set_data("type","transition")
        menu_item.connect("activate", pcontrol.type_selection_changed,
                          state_step_menu,state_transition_menu,st_ddlist)
        type_menu.append(menu_item)
        
        et_ddlist.set_menu(type_menu)
        et_ddlist.set_history(0)
        st_ddlist.set_menu(state_step_menu)
        st_ddlist.set_history(0)

        hbox.pack_start(table,expand = FALSE)
        hbox.set_border_width(3)

        # create sample
        layout = GtkLayout()
        layout.set_size(200,200)
        self.da = GtkDrawingArea()
        self.da.connect("expose_event",self._expose_event)
        self.da.size(200,200)
        layout.put(self.da,0,0)
        self.sample = GtkButton(unicode_to_gtk(_('sample')))
        layout.put(self.sample,60,60)
        hbox.pack_start(layout)
        hbox.show_all()
        # init sample
        pcontrol.default()
        return hbox

    # da callback #

    def _expose_event(self,*args):
        draw_rectangle(args[0].get_window(),args[0].get_style().white_gc,TRUE,
                       0,0,args[0].get_window().width,args[0].get_window().height)
