# Copyright (C) 2006 by Szilveszter Farkas (Phanatic) <szilveszter.farkas@gmail.com>

# 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

import os
import os.path
import sys

try:
    import pygtk
    pygtk.require("2.0")
except:
    pass
try:
    import gtk
    import gtk.glade
except:
    sys.exit(1)

from handler import OliveHandler

# Olive GTK UI version
__version__ = '0.1'

class OliveGtk:
    """ The main Olive GTK frontend class. This is called when launching the
    program. """
    
    def __init__(self):
        # Load the glade file
        self.gladefile = "/usr/share/olive/olive.glade"
        if not os.path.exists(self.gladefile):
            # Load from current directory if not installed
            self.gladefile = "olive.glade"

        self.toplevel = gtk.glade.XML(self.gladefile, 'window_main')
        
        self.window = self.toplevel.get_widget('window_main')
        self.window.show_all()
        
        self.comm = OliveCommunicator(self.toplevel)
        handler = OliveHandler(self.gladefile, self.comm)
        
        # Dictionary for signal_autoconnect
        dic = { "on_window_main_destroy": gtk.main_quit,
                "on_quit_activate": gtk.main_quit,
                "on_about_activate": handler.on_about_activate,
                "on_menuitem_add_files_activate": handler.on_menuitem_add_files_activate,
                "on_menuitem_remove_file_activate": handler.on_menuitem_remove_file_activate,
                "on_menuitem_file_make_directory_activate": handler.not_implemented,
                "on_menuitem_branch_initialize_activate": handler.on_menuitem_branch_initialize_activate,
                "on_menuitem_branch_branch_activate": handler.on_menuitem_branch_branch_activate,
                "on_menuitem_branch_commit_activate": handler.on_menuitem_branch_commit_activate,
                "on_menuitem_branch_push_activate": handler.on_menuitem_branch_push_activate,
                "on_toolbutton_update_clicked": handler.not_implemented,
                "on_toolbutton_commit_clicked": handler.on_menuitem_branch_commit_activate,
                "on_toolbutton_pull_clicked": handler.not_implemented,
                "on_toolbutton_push_clicked": handler.on_menuitem_branch_push_activate,
                "on_treeview_right_row_activated": handler.on_treeview_right_row_activated }
        
        # Connect the signals to the handlers
        self.toplevel.signal_autoconnect(dic)
        
        # Load default data into the panels
        self.treeview_left = self.toplevel.get_widget('treeview_left')
        self.treeview_right = self.toplevel.get_widget('treeview_right')
        self._load_left()
        self._load_right()
    
    def _load_left(self):
        """ Load data into the left panel. (Bookmarks) """
        pass
        
    def _load_right(self):
        """ Load data into the right panel. (Filelist) """
        import olive.backend.fileops as fileops
        
        # Create ListStore
        liststore = gtk.ListStore(str, str, str)
        
        dirs = ['..']
        files = []
        
        # Fill the appropriate lists
        path = self.comm.get_path()
        for item in os.listdir(path):
            if os.path.isdir(path + '/' + item):
                dirs.append(item)
            else:
                files.append(item)
            
        # Sort'em
        dirs.sort()
        files.sort()
        
        # Add'em to the ListStore
        for item in dirs:    
            liststore.append([gtk.STOCK_DIRECTORY, item, ''])
        for item in files:
            liststore.append([gtk.STOCK_FILE, item, fileops.status(path + '/' + item)])
        
        # Create the columns and add them to the TreeView
        self.treeview_right.set_model(liststore)
        tvcolumn_filename = gtk.TreeViewColumn('Filename')
        tvcolumn_status = gtk.TreeViewColumn('Status')
        self.treeview_right.append_column(tvcolumn_filename)
        self.treeview_right.append_column(tvcolumn_status)
        
        # Set up the cells
        cellpb = gtk.CellRendererPixbuf()
        cell = gtk.CellRendererText()
        tvcolumn_filename.pack_start(cellpb, False)
        tvcolumn_filename.pack_start(cell, True)
        tvcolumn_filename.set_attributes(cellpb, stock_id=0)
        tvcolumn_filename.add_attribute(cell, 'text', 1)
        tvcolumn_status.pack_start(cell, True)
        tvcolumn_status.add_attribute(cell, 'text', 2)

class OliveCommunicator:
    """ This class is responsible for the communication between the different
    modules. """
    def __init__(self, toplevel):
        # Get glade main component
        self.toplevel = toplevel
        # Default path
        self._path = os.getcwd()
        
        # Initialize the statusbar
        self.statusbar = self.toplevel.get_widget('statusbar')
        self.context_id = self.statusbar.get_context_id('olive')
        
        # Get the TreeViews
        self.treeview_left = self.toplevel.get_widget('treeview_left')
        self.treeview_right = self.toplevel.get_widget('treeview_right')
    
    def set_path(self, path):
        """ Set the current path while browsing the directories. """
        self._path = path
    
    def get_path(self):
        """ Get the current path. """
        return self._path
    
    def get_selected_right(self):
        """ Get the selected filename. """
        treeselection = self.treeview_right.get_selection()
        (model, iter) = treeselection.get_selected()
        
        if iter is None:
            return None
        else:
            return model.get_value(iter, 1)

    def set_statusbar(self, message):
        """ Set the statusbar message. """
        self.statusbar.push(self.context_id, message)
    
    def clear_statusbar(self):
        """ Clean the last message from the statusbar. """
        self.statusbar.pop(self.context_id)
    
    def refresh_right(self, path=None):
        """ Refresh the file list. """
        import olive.backend.fileops as fileops

        if path is None:
            path = self.get_path()

        # Get ListStore and clear it
        liststore = self.treeview_right.get_model()
        liststore.clear()
        
        dirs = ['..']
        files = []
        
        # Fill the appropriate lists
        for item in os.listdir(path):
            if os.path.isdir(path + '/' + item):
                dirs.append(item)
            else:
                files.append(item)
            
        # Sort'em
        dirs.sort()
        files.sort()
        
        # Add'em to the ListStore
        for item in dirs:    
            liststore.append([gtk.STOCK_DIRECTORY, item, ''])
        for item in files:
            liststore.append([gtk.STOCK_FILE, item, fileops.status(path + '/' + item)])
        
        # Add the ListStore to the TreeView
        self.treeview_right.set_model(liststore)
