import eog, gtk, os

class HelloWorldPlugin(eog.Plugin):

    raw_file_extensions = [ 'cr2', '3fr', 'ari', 'arw', 'srf', 'sr2', 'bay',
        'crw', 'cr2', 'cap', 'iiq', 'eip', 'dcs', 'dcr', 'drf', 'k25', 'kdc',
        'dng', 'erf', 'fff', 'mef', 'mos', 'mrw', 'nef', 'nrw', 'orf', 'ptx',
        'pef', 'pxn', 'r3d', 'raf', 'raw', 'rw2', 'rwl', 'rwz', 'x3f' ]

    def __init__( self ):
        eog.Plugin.__init__( self )

    def activate( self, window ):
        self._window = window

        # insert menu item
        manager = window.get_ui_manager()
        self._action_group = gtk.ActionGroup( "EogRawToolsPluginActions" )
        self._action_group.add_actions( [ ( "EogPluginRunKeepRaw", None,
            _( "Keep Raw Image" ), "K",
            _( "Keep accompanying raw image" ),
            self.on_keep_raw_image ) ] )
        manager.insert_action_group( self._action_group, -1 )
        self._ui_id = manager.add_ui_from_string( """
            <ui>
                <menubar name="MainMenu">
                    <menu name="ToolsMenu" action="Tools">
                        <separator />
                        <menuitem name="EogPluginRawTools"
                            action="EogPluginRunKeepRaw" />
                        <separator />
                    </menu>
                </menubar>
                <popup name="ViewPopup">
                    <separator />
                    <menuitem action="EogPluginRunKeepRaw" />
                    <separator />
                </popup>
            </ui>
        """ )

        # connect to selection change
        thumb_view = window.get_thumb_view()
        self._on_selection_change_id = thumb_view.connect_after( \
            "selection_changed", self.on_selection_change, window )

        # init ui state
        self.update_action_group_sensitivity( window )

    def deactivate( self, window ):

        # remove menu items
        manager = window.get_ui_manager()
        manager.remove_ui( self._ui_id )
        manager.remove_action_group( self._action_group )
        manager.ensure_update()

        # disconnect handlers
        thumb_view = window.get_thumb_view()
        thumb_view.disconnect( self._on_selection_change_id )

    def on_selection_change( self, view, data ):
        self.update_action_group_sensitivity( data )

    def update_action_group_sensitivity( self, window ):

        # do we have just the one selected image? we can't handle multiple
        # images because EogThumbView.get_selected_images() doesn't work.
        thumb_view = window.get_thumb_view()
        self._action_group.set_sensitive( \
            thumb_view.get_n_selected() == 1 )

    def on_keep_raw_image( self, action ):

        # do we have just the one selected image? we can't handle multiple
        # images because EogThumbView.get_selected_images() doesn't work.
        thumb_view = self._window.get_thumb_view()
        if( thumb_view.get_n_selected() == 1 ):

            # get the image
            image = thumb_view.get_first_selected_image()
            if( image != None ):
                self.keep_raw_image( image )

    def keep_raw_image( self, image ):

        fname = image.get_file().get_path()

        # strip the file extension off, ready to search for raw files
        base_fname = image.get_file().get_path()
        pos = base_fname.rfind( '.' )
        if( pos != -1 ):
            base_fname = base_fname[ 0 : pos ]
        
        # check for stupidity
        if( base_fname[ -1 : None ] == '/' ):
            dialog = gtk.MessageDialog( None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO,
                gtk.BUTTONS_CLOSE, "Image is invalid!" )
            dialog.run()
            dialog.destroy()
            return

        # path the raw images will be moved to
        raw_path = os.path.dirname( fname ) + '/raw';

        # loop through valid raw file extensions
        found = False;
        for ext in self.raw_file_extensions + \
             map( lambda x: x.upper(), self.raw_file_extensions ):

            # calculate the name of the raw file and where we would move it to
            src_fname = base_fname + '.' + ext
            dst_fname = raw_path + '/' + os.path.basename( src_fname )

            # look for existing files
            if( os.path.isfile( src_fname ) ):
                found = True;

                # create the raw directory, if it doesn't exist
                if( not os.path.isdir( raw_path ) ):
                    os.mkdir( raw_path );

                # move the raw file in to the raw directory
                os.rename( src_fname, dst_fname )

            # check for already-moved raw files
            elif( os.path.isfile( dst_fname ) ):
                found = True;

        # check we found the raw file
        if( not found ):
            dialog = gtk.MessageDialog( None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO,
                gtk.BUTTONS_CLOSE, "Raw file not found!" )
            dialog.format_secondary_text( "This image doesn't appear to have an accompanying raw file." )
            dialog.run()
            dialog.destroy()
            return
