from PSPApp import *

def ScriptProperties():
    return {
        'Author': u'Corel Corporation',
        'Copyright': u'Copyright (c) 2002-2006 Corel Corporation. All rights reserved.',
        'Description': "Open a file duplicate it and then close the original",
        'Host': u'Paint Shop Pro 9',
        'Host Version': u'9.00'
        }

def Do(Environment):
    # Save off a list of the documents currently open
    OpenDocsBefore = App.Documents
    
    App.Do( Environment, 'FileOpen', {
            'ShowPreview': False, 
            'EnableBrowser': True, 
            'FavFileList': [], 
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Interactive, 
                'AutoActionMode': App.Constants.AutoActionMode.Match,
                'Version': ((9,0,0),1)
                }
            })

    # Get the list of documents open after the call to FileOpen (could be zero, could be one, could be many)
    OpenDocsAfter= App.Documents

    # Loop through the currently open documents, and if a document wasn't open before, duplicate it, and close the original.
    for doc in OpenDocsAfter:
        if not DocWasAlreadyOpen(OpenDocsBefore, doc):
            App.Do( Environment, 'DuplicateWindow', {
                    'GeneralSettings': {
                        'ExecutionMode': App.Constants.ExecutionMode.Default, 
                        'AutoActionMode': App.Constants.AutoActionMode.Match,
                        'Version': ((9,0,0),1)
                        }
                    },
                    doc)

            App.Do( Environment, 'FileClose', {
                    'GeneralSettings': {
                        'ExecutionMode': App.Constants.ExecutionMode.Silent, 
                        'AutoActionMode': App.Constants.AutoActionMode.Match,
                        'Version': ((9,0,0),1)
                        }
                    },
                    doc)


def DocWasAlreadyOpen(OldOpenDocs, doc):
    for olddoc in OldOpenDocs:
        if (doc.Name == olddoc.Name) and (doc.Title == olddoc.Title):
            return 1

    return 0
