
# C:\Python26\python.exe C:\PNWHerbaria\Scripts\renameimage.pyw C:\PNWHerbaria\Images\NewImages\WWB_000015.CR2

import sys
import os
import wx


#---------------------------------------------------------------------------

class MainWindow(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(440,250))
        
        #self.CreateStatusBar() # A Statusbar in the bottom of the window
        
        # Set up the menu:
        filemenu = wx.Menu()

        filemenu.AppendSeparator()
        menuExit = filemenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
        
        helpmenu = wx.Menu()
        menuAbout = helpmenu.Append(wx.ID_HELP, "&About"," Information about this program")
        menuDocumentation = helpmenu.Append(wx.ID_ABOUT, "&Documentation"," Help and Documentation")
        
        # Creat the menu bar and append menus:
        menuBar = wx.MenuBar()
        menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the menu bar
        menuBar.Append(helpmenu,"&Help") # Adding the "helpmenu" to the menu bar
        self.SetMenuBar(menuBar)  # Adding the menu bar to the Frame content.
        
        # Set events:
        self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
        self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
        self.Bind(wx.EVT_MENU, self.OnDocumentation, menuDocumentation)

    def OnExit(self,e):
        self.Close(True)  # Close the frame.

    def OnAbout(self, event):
        description = """This is a simple application for renaming images during image capture 
using a barcode reader.  This program is called from the Canon EOS 
Utility using the Software to Link' option under Preferences."""

        licence = """MIT License:

Copyright (c) 2010, Ben Legler, Consortium of Pacific Northwest Herbaria

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."""

        info = wx.AboutDialogInfo()

        info.SetIcon(wx.Icon('C:\\PNWHerbaria\\Scripts\\Icons\\icon.png', wx.BITMAP_TYPE_PNG))
        info.SetName('Rename Image, PNW Herbaria')
        #info.SetVersion('1.0')
        info.SetDescription(description)
        info.SetCopyright('(C) 2010 Ben Legler')
        info.SetWebSite('http://www.pnwherbaria.org/')
        info.SetLicence(licence)

        wx.AboutBox(info)

    def OnDocumentation(self, e):
        os.startfile(documentationPath)


#---------------------------------------------------------------------------

class MainPanel(wx.Panel):
    def __init__(self, parent):
        
        # Declare some variables for later use:
        self.oldNamePath = ""
        self.oldNameDir = ""
        self.oldName = ""
        self.fileType = ""
        self.newName = ""
        self.newNamePath = ""
        
        wx.Panel.__init__(self, parent)

        # create some sizers
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        grid1 = wx.GridBagSizer(hgap=5, vgap=5)
        
        # Old image name:
        self.oldName = self.GetOldName()
        self.oldNameLabel = wx.StaticText(self, label="Old name:")
        grid1.Add(self.oldNameLabel, pos=(1,0))
        self.oldNameField = wx.StaticText(self, label=self.oldName)
        grid1.Add(self.oldNameField, pos=(1,1))
        
        # New image name (barcode):
        self.newNameLabel = wx.StaticText(self, label="New Name:")
        grid1.Add(self.newNameLabel, pos=(2,0))
        self.newNameField = wx.TextCtrl(self, value='', size=(150,-1))
        grid1.Add(self.newNameField, pos=(2,1))
        self.newNameField.Bind(wx.EVT_KILL_FOCUS, self.Rename)
        
        # Rename button:
        self.renameBtn = wx.Button(self, label="Rename")
        grid1.Add(self.renameBtn, pos=(2,2))
        self.Bind(wx.EVT_BUTTON, self.Rename, self.renameBtn)
        
        self.newNameHint = wx.StaticText(self, label="(don't include file extension)")
        grid1.Add(self.newNameHint, pos=(3,1))
        
        # add a spacer between the button and the instructions:
        grid1.Add((10, 10), pos=(4,0))
        
        self.instructions1 = wx.StaticText(self, label="  INSTRUCTIONS:")
        self.instructions2 = wx.StaticText(self, label="    1) Double-check that the cursor is in the New Name field.")
        self.instructions3 = wx.StaticText(self, label="    2) Then use the barcode reader to scan the barcode.")
        self.instructions4 = wx.StaticText(self, label="    3) If you need to add a suffix, use the keyboard to manually edit the new name.")
        self.instructions5 = wx.StaticText(self, label="    4) Then click the Rename button to rename the image and close this window.")
        
        mainSizer.Add(grid1, 0, wx.ALL, 5)
        
        mainSizer.Add(self.instructions1, 0, wx.ALIGN_LEFT)
        mainSizer.Add(self.instructions2, 0, wx.ALIGN_LEFT)
        mainSizer.Add(self.instructions3, 0, wx.ALIGN_LEFT)
        mainSizer.Add(self.instructions4, 0, wx.ALIGN_LEFT)
        mainSizer.Add(self.instructions5, 0, wx.ALIGN_LEFT)
        
        self.SetSizerAndFit(mainSizer)
        
    def GetOldName(self):
        try:
            self.oldNamePath = sys.argv[1]
        except:
            return ""
        head, tail = os.path.split(self.oldNamePath)
        self.oldNameDir = head
        self.oldName = tail
        self.fileType = tail.split(".")[1]
        return tail
    
    def Rename(self, event):
        if self.oldNamePath == "":
            dial = wx.MessageDialog(None, 'ERROR: there is no image to rename (old name is blank).', 'Error', wx.OK | wx.ICON_ERROR)
            dial.ShowModal()
            self.newNameField.SetFocus()
            self.newNameField.SetSelection(-1,-1)
            wx.Exit()
            return
        if os.path.exists(self.oldNamePath) == False:
            dial = wx.MessageDialog(None, 'ERROR: No image file exists for the old name. Image was not renamed.', 'Error', wx.OK | wx.ICON_ERROR)
            dial.ShowModal()
            self.newNameField.SetFocus()
            self.newNameField.SetSelection(-1,-1)
            wx.Exit()
            return
        self.newName = self.newNameField.GetValue()
        self.newNamePath = os.path.join(self.oldNameDir, self.newName + "." + self.fileType)
        if self.newName == "":
            dial = wx.MessageDialog(None, 'ERROR: new name is blank.  Image was not renamed.', 'Error', wx.OK | wx.ICON_ERROR)
            dial.ShowModal()
            self.newNameField.SetFocus()
            return
        renameImage = True
        if os.path.exists(self.newNamePath):
            renameImage = False
            dial = wx.MessageDialog(None, 'An image with this file name already exists.  Do you want to overwrite it?', 'Warning', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_EXCLAMATION)
            dialInput = dial.ShowModal()
            if dialInput == wx.ID_YES:
                renameImage = True
        if renameImage == True:
            if os.path.exists(self.newNamePath) and self.oldNamePath != self.newNamePath:
                os.remove(self.newNamePath)
            if os.path.exists(self.oldNamePath) and self.oldNamePath != self.newNamePath:
                os.rename(self.oldNamePath, self.newNamePath)
            wx.Exit()  # Close the application only if the image was renamed.
            return
        else:
            self.newNameField.SetFocus()
            self.newNameField.SetSelection(-1,-1)


#---------------------------------------------------------------------------


app = wx.App(False)
frame = MainWindow(None, "Rename Image, PNW Herbaria")
panel = MainPanel(frame)
frame.Show()
app.MainLoop()
