# -*- coding: iso-8859-15 -*-


# Glasnost
# By: Odile Bénassy <obenassy@entrouvert.com>
#     Romain Chantereau <rchantereau@entrouvert.com>
#     Nicolas Clapiès <nclapies@easter-eggs.org>
#     Pierre-Antoine Dejace <padejace@entrouvert.be>
#     Thierry Dulieu <tdulieu@easter-eggs.com>
#     Florent Monnier <monnier@codelutin.com>
#     Cédric Musso <cmusso@easter-eggs.org>
#     Frédéric Péters <fpeters@entrouvert.be>
#     Benjamin Poussin <poussin@codelutin.com>
#     Emmanuel Raviart <eraviart@entrouvert.com>
#     Sébastien Régnier <regnier@codelutin.com>
#     Emmanuel Saracco <esaracco@easter-eggs.com>
#
# Copyright (C) 2000, 2001 Easter-eggs & Emmanuel Raviart
# Copyright (C) 2002 Odile Bénassy, Code Lutin, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Frédéric Péters, Benjamin Poussin, Emmanuel Raviart,
#     Emmanuel Saracco & Théridion
# Copyright (C) 2003 Odile Bénassy, Romain Chantereau, Nicolas Clapiès,
#     Code Lutin, Pierre-Antoine Dejace, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Florent Monnier, Cédric Musso, Ouvaton, Frédéric Péters,
#     Benjamin Poussin, Rodolphe Quiédeville, Emmanuel Raviart, Sébastien
#     Régnier, Emmanuel Saracco, Théridion & Vecam
#
# 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.

#CONTENT : The glasnost-gui Main Window
#Dejace Pierre-Antoine 

from tools import *

import GlasnostGui
import LoginBox
import MiniBrowser

class GnomeMainWindow:
    def __init__(self):
        gnome.init('glasnost', '0.1')
        xmlGlade = glade.XML(context.getVar('gladeFileName'), 'MainWindow')
        self._window = xmlGlade.get_widget('MainWindow')
        optionMenu = xmlGlade.get_widget('optionmenu-serverroles')

        menu = gtk.Menu()
        menu.show()
        optionMenu.set_menu(menu)
        
        roles = []
        for role in context.getVar('knownRoles'):
            #try:
            w = getGtkForServerRole(role)
            #except:
                #continue
            if not hasattr(w, 'canGetObjects') or \
                        not hasattr(w, 'objectsNameCapitalized'):
                continue
            if not w.canGetObjects():
                continue
        
            roles.append(w)

        roles.sort(lambda x, y: locale.strcoll(_(x.objectsNameCapitalized),
                                               _(y.objectsNameCapitalized)) )
        for w in roles:
            menuitem = gtk.MenuItem(_(w.objectsNameCapitalized))
            menuitem.set_data('role', w.serverRole)
            menuitem.connect('activate', self.onChangeRole, menuitem.get_data('role'))
            menu.add(menuitem)
            menuitem.show()       

        xmlGlade.signal_connect('on_exit', self.delete_event)

        self.treeviewObjects = xmlGlade.get_widget('treeview-objects')
        model = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING)
        self.treeviewObjects.set_model(model)
        self.treeviewObjects.set_rules_hint(gtk.TRUE)
        self.treeviewObjects.set_search_column(0)
        column = gtk.TreeViewColumn('Label', gtk.CellRendererText(), text = 0)
        self.treeviewObjects.append_column(column)
        self.treeviewObjects.get_selection().connect('changed', self.onObjectSelected)

        self.objectLabel = xmlGlade.get_widget('label-objectLabel')
        self.objectLabel.set_text('')

        self.frameObject = xmlGlade.get_widget('frame-object')
        self.sclWinObject = xmlGlade.get_widget('sclwin-object')
        self.objectTable = None

        paned = xmlGlade.get_widget('hpaned-content')
        paned.set_position(200)

        self.appbar = xmlGlade.get_widget('appbar')

        self._window.resize(800,600)
        self._window.show()


    def show_all(self):
        pass

    def delete_event(self, *args):
        return gtk.main_quit()

    def onChangeRole(self, *args):
        proxy = getProxyForServerRole(args[1])
        self.objectIds = proxy.getObjectIds()
        model = self.treeviewObjects.get_model()
        model.clear()

        percentage = 0
        if self.objectIds:
            step = 1.0/len(self.objectIds)

        for id in self.objectIds:
            label = proxy.getObjectLabelTranslated(id, context.getVar('readLanguages'))
            iter = model.append()
            model.set(iter, 0, utf8(label), 1, id)

            percentage += step
            self.appbar.set_progress_percentage(percentage)
            while gtk.events_pending():
                gtk.mainiteration()

        self.objectLabel.set_text(_('Nothing selected'))
        self.appbar.set_progress_percentage(0)

    def onObjectSelected(self, selection):
        s = selection.get_selected()
        if not s:
            return
        model, iter = s
        if iter is None:
            return
        path = model.get_path(iter)
        objectId = self.objectIds[path[0]]
        object = getObject(objectId)
        self.objectLabel.set_markup('<big><b>%s</b></big>' % utf8(object.getLabel()) )
        if self.objectTable:
            self.objectTable.destroy()
        self.objectTable = object.getViewTable()
        self.objectTable.show_all()
        #self.frameObject.add(self.objectTable)
        self.sclWinObject.add_with_viewport(self.objectTable)

        
class MainWindow(gtk.Window):
        
    def delete_event(self, widget, event, data=None):
        gtk.main_quit()
        return FALSE
    
    def re_init(self):
        refB = context.getVar('gtkMiniBrowser_instance')
        refDM = context.getVar('gtkDirectMenu_instance')
        refMW = context.getVar('gtkMainWindow_instance')
        
        if refB:
            refB.destroy()
            context.setVar('gtkMiniBrowser_instance', None)
            refB = MiniBrowser.MiniBrowser(None,'favorite')
            context.setVar('gtkMiniBrowser_instance',refB)
            self.vbox_sec2.pack_start(refB, TRUE, TRUE, 0)
            
        if refDM:
            refDM.destroy()
            context.setVar('gtkDirectMenu_instance', None)
            
 
    def browse_obj(self, obj_type):
        
        #References towards context
        refB = context.getVar('gtkMiniBrowser_instance')
        refDM = context.getVar('gtkDirectMenu_instance')
        
        #MiniBrowser instance
        if refB:
            refB.destroy()
            refB = MiniBrowser.MiniBrowser(obj_type)
            context.setVar('gtkMiniBrowser_instance',refB)
        else:
            refB = MiniBrowser.MiniBrowser(obj_type)
            context.setVar('gtkMiniBrowser_instance',refB)
        
        #DirectMenu instance
        if refDM:
            refDM.destroy()
            refDM = GlasnostGui.DirectMenu(obj_type)
            context.setVar('gtkDirectMenu_instance',refDM)
        else:
            refDM = GlasnostGui.DirectMenu(obj_type)
            context.setVar('gtkDirectMenu_instance',refDM)
        
        #packing
        self.vbox_sec2.pack_start(refB, TRUE, TRUE, 0)
        self.vbox_sec1.pack_start(refDM, TRUE, FALSE, 0)

    def __init__(self):
        gtk.Window.__init__(self,gtk.WINDOW_TOPLEVEL)
        #self.set_position(gtk.WIN_POS_CENTER)
        self.connect("delete_event", self.delete_event)
        
        context.setVar('gtkMainWindow_instance',self)
        #DaGlobalEvent = GlasnostGui.GlobalEvent()
        if context.getVar('gtkGlobalEvent_instance') is None:
            context.setVar('gtkGlobalEvent_instance', GlasnostGui.GlobalEvent())
        
        #gettext section
        #__builtins__.__dict__['_'] = gettext.gettext
        #gettext.bindtextdomain('glasnost-gui', '/usr/share/locale')
        #lang1 = gettext.translation('glasnost-gui','/usr/share/locale',['fr'])
        #lang1.install()
        
        #BoX Section
        vbox = gtk.VBox(FALSE,2)
        vbox.show()
        
        self.vbox_sec1 = gtk.VBox(FALSE,2)
        self.vbox_sec1.show()
        self.vbox_sec2 = gtk.VBox(FALSE,2)
        self.vbox_sec2.show()

        #Paned sectio
        hpane = GlasnostGui.HPaned(100,self.vbox_sec1,self.vbox_sec2)
        
        #ComboBoX and Label section
        MsgBar = GlasnostGui.StatusBar()
        
        self.optionMenu_sec1 = GlasnostGui.ServerRolesOptionMenu(MsgBar,self)
        self.vbox_sec1.pack_start(self.optionMenu_sec1,FALSE,FALSE,0)
        
        #MenuBar section
        Menu_handle = gtk.HandleBox()
        Menu_handle.show()
        Menu_Bar = GlasnostGui.MenuBar()
        Menu_handle.add(Menu_Bar)
        
        vbox.pack_start(Menu_handle,FALSE,FALSE,0)
        
        #Window settings section
        self.set_resizable(1)
        self.set_title('Glasnost - Your Gateway to E-Democratie Heavens')
        self.set_default_size(800,600)
        self.activate_focus()
        
        #Initial Browser instance
        refB = MiniBrowser.MiniBrowser(None,'favorite')
        context.setVar('gtkMiniBrowser_instance',refB)
        self.vbox_sec2.pack_start(refB, TRUE, TRUE, 0)

        #Packing
        vbox.pack_start(hpane,TRUE,TRUE,1)
        vbox.pack_start(MsgBar,FALSE,FALSE,0)
        
        self.add(vbox)
        #self.unmaximize()
        #self.maximize()


if 1 and gnome and glade:
    MainWindow = GnomeMainWindow

