import Foundation
import AppKit
import imp
import objc
import os
import shutil
import sys
import StringIO

#objc.registerPlugin('PythonPlugin')

NSObject = objc.lookUpClass('NSObject')

class ACPythonPlugin (NSObject):
    
    def plugin(cls):
        return ACPythonPlugin.alloc().init()
    
    plugin = classmethod(plugin)
    
    def installPluginAtPath(self, thePluginManager, theFullPath):
        
        theFilename = os.path.basename(theFullPath)
        
        if os.path.splitext(theFilename)[-1] == '.py' or os.path.splitext(theFilename)[-1] == '.acpy':
            theModuleName = os.path.splitext(theFilename)[0]
            
            suffix = '.py'
            if os.path.splitext(theFilename)[-1] == '.acpy':
                suffix = '.acpy'
            
            try:
                theModule = imp.load_module(theModuleName, file(theFullPath), theFullPath, ('.py', 'U', 1),)
                
                if not hasattr(theModule, 'ACScriptMenuTitle'):
                    return
                if not hasattr(theModule, 'ACScriptSuperMenuTitle'):
                    return
                
                theMenuTitle = theModule.ACScriptMenuTitle
                theSuperMenuTitle = theModule.ACScriptSuperMenuTitle
                
                # get shortcut key (optional)
                try:
                    theShortcutKey = theModule.ACShortcutKey
                    theShortcutMask = theModule.ACShortcutMask
                    # set Modifier Flags
                    try:
                        theShortcutMask = int(theShortcutMask)
                    except:
                        theShortcutMask = self.decodeShortcutMask(theShortcutMask)
                except:
                    theShortcutKey = ''
                    theShortcutMask = 0
                
                
                # find out if it goes in the actions menu
                try:
                    isAction = theModule.ACIsAction
                except:
                    isAction = False
                
                if isAction:
                    thePluginManager.addActionMenuTitle_withSuperMenuTitle_target_action_keyEquivalent_keyEquivalentModifierMask_userObject_(theMenuTitle, theSuperMenuTitle, self, "handleRunPlugin:userObject:", theShortcutKey, theShortcutMask, theModuleName)
                else:
                    thePluginManager.addFilterMenuTitle_withSuperMenuTitle_target_action_keyEquivalent_keyEquivalentModifierMask_userObject_(theMenuTitle, theSuperMenuTitle, self, "handleRunPlugin:userObject:", theShortcutKey, theShortcutMask, theModuleName)
                
                thePluginDict = dict(
                    name = theModuleName,
                    path = theFullPath)

                self.plugins[theModuleName] = thePluginDict


            except Exception, e:
                print 'Failed to load plugin: %s' % theFullPath
                print e
    
        
        
    
    def willRegister_(self, thePluginManager):
        
        self.plugins = {}
        
        for theFilename in os.listdir(self.scriptsDirectory):
            theFullPath = os.path.join(self.scriptsDirectory, theFilename)
            self.installPluginAtPath(thePluginManager, theFullPath)
        
        libFolder = "/Library/Application Support/Acorn/Plug-Ins/"
        
        if os.path.isdir(libFolder):
            for theFilename in os.listdir(libFolder):
                theFullPath = os.path.join(libFolder, theFilename)
                self.installPluginAtPath(thePluginManager, theFullPath)
        
        
    
    def didRegister(self):
        
        pass
    
    def worksOnShapeLayers_(self, userObject):
        
        thePlugin = self.plugins[userObject]
        theModule = imp.load_module(thePlugin['name'], file(thePlugin['path']), thePlugin['path'], ('.py', 'U', 1),)
        
        if hasattr(theModule, "layerAction"):
            return True

        return False


    def handleRunPlugin_userObject_(self, image, userObject):
        
        thePlugin = self.plugins[userObject]
        theModule = imp.load_module(thePlugin['name'], file(thePlugin['path']), thePlugin['path'], ('.py', 'U', 1),)
        
        if hasattr(theModule, "layerAction"):
            theModule.layerAction(AppKit.NSDocumentController.sharedDocumentController().currentDocument().currentLayer())
            return None
        
        return theModule.main(image)
        
    
    def getScriptsDir(self):
        if not self.__dict__.has_key('_scriptsDirectory'):
            theScriptPluginDir = os.path.expanduser('~/Library/Application Support/Acorn/Plug-Ins')
            if not os.path.isdir(theScriptPluginDir):
                 os.makedirs(theScriptPluginDir)
            _scriptsDirectory = theScriptPluginDir
        return _scriptsDirectory
    scriptsDirectory = property(getScriptsDir)
    
    def decodeShortcutMask(self,maskStr):
        shortcutMask = 0
        for mask in maskStr.split():
            if mask.lower() == "shift":
                shortcutMask += 1 << 17
            elif mask.lower() == "control" or mask.lower() == "ctrl":
                shortcutMask += 1 << 18
            elif mask.lower() == "alt" or mask.lower() == "opt" or mask.lower() == "option":
                shortcutMask += 1 << 19
            elif mask.lower() == "command":
                shortcutMask += 1 << 20
        return shortcutMask
