# debpartial_mirror_ui - User Interface for partial debian mirror package tool
# (c) 2006 Otavio Salvador <otavio@debian.org>
# (c) 2006 Marco Presi <zufus@debian.org>
#
# 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


from gtk import VBox, HBox, Notebook, VPaned, Label, \
     TreeView, TreeIter, TreeViewColumn, TreeStore, \
     CellRendererText, Frame, SHADOW_IN, SELECTION_SINGLE

import gobject

import ConfigParser

from debpartial_mirror import Config


class PropertyEditor (TreeView):
    """ A TreeView with property/value pairs """


    __gsignals__ = dict(property_changed=(gobject.SIGNAL_RUN_FIRST,
                                          gobject.TYPE_NONE,
                                          (gobject.TYPE_STRING,)))


    def __init__ (self, cnf):
        super (PropertyEditor, self).__init__()

        self.cnf = cnf
        self.set_property ('visible', True)
        self.set_property ('can_focus', True)
        self.set_property ('headers_visible', True)
        self.set_property ('enable_search', True)
        self.set_property ('reorderable', True)
        self.set_property ('rules_hint',False)
        self.set_property ('fixed_height_mode', False)
        self.set_property ('hover_selection', False)
        self.set_property ('hover_expand', False)

        (self.COLUMN_PROP,
         self.COLUMN_VALUE) = range(2)


        self.model = TreeStore (gobject.TYPE_STRING,
                                gobject.TYPE_STRING)
        
        renderer = CellRendererText ()
        renderer.set_property ("xalign", 0.0)

        column = TreeViewColumn('Key',
                                renderer,
                                text=self.COLUMN_PROP)

        column.set_clickable(False)
        column.set_sort_column_id(self.COLUMN_PROP)
        self.append_column(column)

        column = TreeViewColumn('Value',
                                renderer,
                                text=self.COLUMN_VALUE)

        column.set_clickable(False)
        column.set_sort_column_id(self.COLUMN_VALUE)
        self.append_column(column)

        select = self.get_selection ()
        select.set_mode (SELECTION_SINGLE)
        select.connect ('changed', self.property_selected_cb)


        self.expand_all()
        self.set_rules_hint(True)
        self.show_all()

    def property_selected_cb (self, selection):
        (model, iter) = selection.get_selected ()
        if isinstance (iter, TreeIter): 
            print "%s selected\n" % model.get_value (iter, self.COLUMN_PROP)
            self.emit ('property_changed', model.get_value (iter, self.COLUMN_PROP))



    def update_property_editor (self, b_name):
        """ A method to update the propety/value pair
        after that a backend is selected """

        print "update_property_editor: %s" % b_name


        try:
            options = self.cnf.options(b_name)
            self.model.clear ()
            for b in options:
                print "Adding %s" %  b
                self.iter = self.model.append (None)
                self.model.set (self.iter,
                                self.COLUMN_PROP, b,
                                self.COLUMN_VALUE, self.cnf.get_option(b, b_name))
                
        except ConfigParser.NoSectionError:
            # If the selected row was not a backend, we simply ignore it
            if b_name == "<b>Global</b>":
                self.update_property_editor ('GLOBAL')

        self.set_model (self.model)





class PropertyDescriptor (HBox):
    """A display widget that shows a description of the
    selected property """


    prop = {'mirror_dir': 'Filesystem path where the partial mirror is built',
            'components': 'Specify which archives sections should be mirrored',
            'get_packages':'Add description',
            'distributions': 'list of distributions (stable, testomg,..) to mirror',
            'get_provides': 'Add description',
            'get_recommends': 'Add description',
            'architectures': 'list of architectures to mirrors',
            'get_suggests': 'Add description',
            'get_sources': 'Add description'}


    def __init__ (self, debug=False):
        super (PropertyDescriptor, self).__init__ ()

        self._debug_mode = debug

        #self._default_msg = Label("Select a config file section.")
        self._prop_des    = ""
        self._prop_name   = ""
        
        self.prop_name_label = Label ("Name:")
        self.prop_desc_label = Label ("Description:")

        self.prop_name_text = Label ()
        self.prop_desc_text = Label ()
        
        
        label_box = VBox ()
        desc_box  = VBox ()

        label_box.pack_start (self.prop_name_label)
        label_box.pack_start (self.prop_desc_label)

        desc_box.pack_start (self.prop_name_text)
        desc_box.pack_start (self.prop_desc_text)
        
        self.pack_start (label_box)
        self.pack_start (desc_box)

        self.show_all ()

    def update_property_descriptor (self, w, prop_name):
        """ Modify the labels to describe the property selected in
        the configuration editor"""


        print "update_property_descriptor: %s" % prop_name

        try:
            prop_desc = self.prop[prop_name]
            self.prop_name_text.set_text ("%s" % prop_name)
            self.prop_desc_text.set_text ("%s" % prop_desc)

        except KeyError, e:
            print "Errore %s" % e



class ConfigEditor (VPaned):
    """A widget to read/edit the configuration files """

    def __init__ (self, cnf, debug=False):
        super (ConfigEditor, self).__init__()

        self._debug_mode = debug
        
        self.l = PropertyDescriptor ()
        self.p = PropertyEditor (cnf)

        self.p.update_property_editor ('GLOBAL')
        #self.update_label (self.l)

        pframe = Frame ()
        lframe = Frame ()

        pframe.set_shadow_type (SHADOW_IN)
        lframe.set_shadow_type (SHADOW_IN)

        pframe.add (self.p)
        lframe.add (self.l)
        
        self.add1 (pframe)
        self.add2 (lframe)

        self.p.connect ('property_changed', self.l.update_property_descriptor)


    
        self.show_all ()


    def update_property_editor (self, b_name):
        self.p.update_property_editor (b_name)

    def update_label (self, l):
        """ Change the label text """

        l.set_text ('Select a config file section.')



