#!/usr/bin/env python

# Rather messy first attempt at a bit of Python
# pete morgan = - pm@daffodil.uk.com

import pygtk
pygtk.require('2.0')

import gtk
import gtk.glade

import os

# Check for new pygtk: this is new class in PyGtk 2.4
if gtk.pygtk_version < (2,3,90):
   print "PyGtk 2.3.90 or later required for this example"
   raise SystemExit

################################################################################
#
# DiffChooser - Dialog for selecting files/dirs to compare
#
################################################################################

class DiffChooser:

    def __init__(self, parentapp=None ):
        self.parentapp = parentapp

        # Enable file history to .ini
        self.history_enabled = True
        if self.history_enabled:
            from configobj import ConfigObj
            self.history_file_name = './history_file.ini'
            self.historyFileObj = ConfigObj(self.history_file_name)

        # Load Glade file and set the mainWIndow of the widget
        self.wTree = gtk.glade.XML("glade2/diff_chooser.glade")
        self.mainWindow = self.wTree.get_widget('dialog-diff-chooser')
        self.mainWindow.resize(1000, 700)
        self.mainWindow.set_title('Diff Chooser')
        if self.parentapp:
            self.mainWindow.set_transient_for(parentapp.widget)

        # Set the event handlers - mappings
        eventHandlers = {      "on_winWindow_destroy": gtk.main_quit,
                               "on_file_compare_toggled": self.on_set_compare_mode,
                               "on_dir_compare_toggled": self.on_set_compare_mode,
                               "on_three_way_toggled": self.on_set_three_way,
                               "on_swap_button_clicked": self.on_swap_button_clicked,
                               "on_cancel_clicked": self.on_cancel_clicked,
                               "on_compare_clicked": self.on_compare_clicked
                               }
        self.wTree.signal_autoconnect( eventHandlers )

        # some objects as vars
        self.tableTop = self.wTree.get_widget('table-top')
        self.notebook = self.wTree.get_widget('notebook')
        self.notebook.remove_page(0) # nuke paceholder/design page
        self.notebook.show()

        # top table elements
        self.entryLabels = {}
        self.entryCombos = {}
        self.historyStores = {} # foe entryCombos{}
        self.entryTexts = {}
        # notebook  contents
        self.labelTabs = {}
        self.fileChoosers = {}

        # initiate and create widgets
        self.compare_by_dir = True # Do checkbox.. maybe an option later
        self.table_row_count = 0
        self.create_file_choosers(0,'Other')
        self.create_file_choosers(1,'Original')
        self.create_file_choosers(2,'Mine')
        self.on_set_three_way() # defaults to false
        self.notebook.set_current_page(1)


    ## file has changes in one of the fileChoosers
    def selection_changed(self, fileChooser ,idx ):
        if fileChooser.get_filename():
            self.entryTexts[idx].set_text( fileChooser.get_filename() )
            self.check_compare_button_state()

    # This checks both entries are files or directory. enables/disables the compare button
    def check_compare_button_state(self):
        if self.entryTexts[1].get_text() == self.entryTexts[2].get_text():
            state = False
        elif os.path.isfile(self.entryTexts[1].get_text() ) and os.path.isfile(self.entryTexts[2].get_text() ):
            state = True
        elif os.path.isdir(self.entryTexts[1].get_text() ) and os.path.isdir(self.entryTexts[2].get_text() ):
            state = True
        else:
            state = False

        self.wTree.get_widget('compare-button').set_sensitive(state)

    # COmpare/OK pressed
    def on_compare_clicked(self, widget, *arg):
        # get paths to retunr, are first if three way
        paths = [self.entryTexts[1].get_text(), self.entryTexts[2].get_text()]
        if self.three_way:
            paths.insert(0, self.entryTexts[0].get_text())

            # loops the Stores and save to config file
        if self.history_enabled:
            for idx in (0,1,2):
                self.historyStores[idx].insert( 1, [self.entryTexts[idx].get_text() ] ) # add curr entry
                key = 'history_%s' % idx
                self.historyFileObj[key] = []
                for elem in  range( 1, len(self.historyStores[idx]) ):
                   self.historyFileObj[key].append( self.historyStores[idx][elem][0] )
            self.historyFileObj.write()

        # place paths in parent object
        if self.parentapp:
            if os.path.isdir(self.entryTexts[1].get_text() ):
                self.parentapp.append_dirdiff(paths)
            elif os.path.isfile( self.entryTexts[1].get_text() ):
                self.parentapp.append_filediff(paths)
            else:
                self.parentapp.append_vcview(paths)
        self.mainWindow.destroy()

    # cancel pressed
    def on_cancel_clicked(self,widget,*arg):
        self.mainWindow.destroy()

    # History item selected
    def on_history_selected(self,widget,idx):
        index = self.entryCombos[idx].get_active()
        if index > -1:
            self.entryTexts[idx].set_text( self.historyStores[idx][index][0])
            self.fileChoosers[idx].set_filename( self.historyStores[idx][index][0])
            self.notebook.set_current_page(idx)
        return


    # Create the table and motebook controls
    def create_file_choosers(self, idx, caption):
        # create liststores
        self.historyStores[idx] = gtk.ListStore(str)
        self.historyStores[idx].append(['-- select previous --'])
        if self.history_enabled:
            key = 'history_%s' % idx
            # check there are config items and add them
            try:
                hist = self.historyFileObj[key]
                for h in hist:
                    self.historyStores[idx].append( [h] )
            except:
                print "no var"

        # populate notebook
        self.fileChoosers[idx] = gtk.FileChooserWidget(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
        self.fileChoosers[idx].show()
        self.labelTabs[idx] = gtk.Label(caption)
        self.labelTabs[idx].set_padding(15, 2)
        self.labelTabs[idx].show()
        self.notebook.append_page( self.fileChoosers[idx], self.labelTabs[idx] )

        # populate top table
        self.entryLabels[idx] = gtk.Label(caption)
        self.entryLabels[idx].show()
        self.tableTop.attach(self.entryLabels[idx], 0, 1, self.table_row_count, 1 + self.table_row_count, gtk.SHRINK)

        self.entryTexts[idx] = gtk.Entry()
        self.entryTexts[idx].show()
        self.tableTop.attach(self.entryTexts[idx], 1, 2, self.table_row_count, 1 + self.table_row_count)

        self.entryCombos[idx] = gtk.ComboBox(self.historyStores[idx]) #gtk.combo_box_new_text()
        self.entryCombos[idx].set_active(0) # maybe this should be #1
        cell = gtk.CellRendererText()
        self.entryCombos[idx].pack_start(cell, True)
        self.entryCombos[idx].add_attribute(cell, 'text', 0)
        self.entryCombos[idx].show()
        self.tableTop.attach(self.entryCombos[idx], 2, 3, self.table_row_count, 1 + self.table_row_count)

        self.fileChoosers[idx].connect( 'selection-changed', self.selection_changed, idx)
        self.entryCombos[idx].connect("changed",self.on_history_selected, idx)
        self.table_row_count += 1


    # dir/file aradios have been toggles
    def on_set_compare_mode(self, widget, data=None):
        self.compare_by_dir =  self.wTree.get_widget('dir-compare').get_active()
        if self.compare_by_dir:
           mode = gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER
        else:
           mode = gtk.FILE_CHOOSER_ACTION_OPEN
        for i in (0,1,2):
            self.fileChoosers[i].set_action(mode)

    # Enables or disables the "Other" control when check_box is clicked
    def on_set_three_way(self, *args):
        self.three_way = self.wTree.get_widget('three-way').get_active()
        self.wTree.get_widget('swap-button').set_sensitive( not self.three_way)
        self.labelTabs[0].set_sensitive( self.three_way )
        self.entryTexts[0].set_sensitive( self.three_way )
        self.entryCombos[0].set_sensitive( self.three_way )
        self.fileChoosers[0].set_sensitive( self.three_way )

    # Swaps the Original, Mine when button pressed
    def on_swap_button_clicked(self,*args):
        stash_path = self.entryTexts[2].get_text()
        self.entryTexts[2].set_text( self.entryTexts[1].get_text() )
        self.entryTexts[1].set_text(stash_path)
        self.fileChoosers[1].set_filename( self.entryTexts[1].get_text())
        self.fileChoosers[2].set_filename( self.entryTexts[2].get_text())

if __name__ == "__main__":
    diffChooser = DiffChooser(None)

    gtk.main()
