######################
#
#   PyBlock class
#
######################

import PSPTools
from PSPTools import *

class PyBlock:
    def __init__(self, cmd, block):
        self.commandType = cmd            # type of block found
        self.block = block                # lines of text for block
        self.modified = 0                 # has block been modified.
        self.exeModeAction = 'nochange'   # code indicating change of execution mode on write
        self.newCmdBody = 'nochange'      # if the user edited a command thru its dialog, then this
                                          # string will have the updated parameters
        self.editable = 0                 # for commands only: is this command editable
        self.deleted = 0
        self.commentbutton = 666
        return

    # this function should toggle
    def commentHandler(self):
        # if we are commenting, then copy the block to newCmdBody with comment markers
        # otherwise just copy the block to newCmdBody with no modifications
        commented = not self.commentAction.get()
        copied = false

        self.modified = 1            

        print 'COMMENTED'
        print commented
        print 'end COMMENTED'

        # update the text
        if commented :
            self.commentbutton.config(text='Disabled')
        else:
            self.commentbutton.config(text='Enabled ')
        
        if  self.newCmdBody == 'nochange':
            self.newCmdBody = self.block
            copied = true
            
    # comment the block
        if (self.commandType == 'PSPCmd' and commented) or (self.commandType == 'CmtedPSPCmd' and commented and not copied):
            if self.newCmdBody == 'nochange':
                self.newCmdBody = self.block

            # insert a comment marker at the beginning
            self.newCmdBody = '#' + self.newCmdBody

            insertlist = []
            pos = 0

            # if we find a newline char, put its index location into a list
            for x in self.newCmdBody:
                if x == chr(10):
                    insertlist += [pos]
                pos += 1

            blockLen = len(self.newCmdBody)
            stringCtr = blockLen
            posCtr = len(insertlist)-1

            # cycle backwards thru the block, inserting a '#' at all marked locations
            while posCtr>=0:
                self.newCmdBody = self.newCmdBody[:insertlist[posCtr]+1] + '#' + self.newCmdBody[insertlist[posCtr]+1:]
                posCtr -= 1

            self.modified = 1

        # remove comments from the block
        elif (self.commandType == 'CmtedPSPCmd' and not commented) or (self.commandType == 'PSPCmd' and not commented and not copied):
            if self.newCmdBody == 'nochange':
                self.newCmdBody = self.block
            # deletelist is a list of char positions that we will delete
            deletelist = []

            blockSize = len(self.newCmdBody)

            pos = 0
            # mark the position of all hash marks in the command text for deletion
            while pos < blockSize-1:
                while self.newCmdBody[pos] == '#' or self.newCmdBody[pos] == ' ' or self.newCmdBody[pos] == chr(9):
                    if self.newCmdBody[pos] == '#':
                        deletelist += [pos]
                    pos += 1

                while self.newCmdBody[pos] != chr(10) and pos < blockSize-1:
                    pos += 1
                if self.newCmdBody[pos] == chr(10):
                    pos += 1

            pos = len(deletelist)-1
            # delete the hash marks from the command text
            while pos >= 0:
                delIndex = deletelist[pos]
                cmdText = self.newCmdBody
                self.newCmdBody = cmdText[:delIndex] + cmdText[delIndex+1:]
                pos -= 1

            self.modified = 1

    def exeModeHandler(self, newmode):
        if self.newCmdBody == 'nochange':
            self.newCmdBody = self.block
        self.newCmdBody = PSPTools.changeExecutionMode(self.newCmdBody, newmode)
        self.modified = 1
        print newmode

    def selectionHandler():
        print self.selected.get()

    def dump(self):
        return (self.block, self.commandType)

    def write(self, fp):
        fp.write(self.block)
        return

    def edit(self):
        return


#############################################
class PyScript(PyBlock):
    def __init__(self, cmd, block, parameters):
        # initialize the base class first
        PyBlock.__init__ (self, cmd, block)
        
        # init self.  

        if parameters.has_key("Author"):
            self.auth = parameters["Author"]
        else:
            self.auth = ""
        if parameters.has_keyself("Copyright"):
            self.copy = parameters["Copyright"]
        else:
            self.copy = ""
        if parameters.has_key("Description"):
            self.desc = parameters("Description")
        else:
            self.desc = ""
        if parameters.has_key("Host"):
            self.host = parameters("Host")
        else:
            self.host = ""
        if parameters.has_key("Host Version"):
            self.hostver = parameters["Host Version"]
        else:
            self.hostver = ""

    def write(self, fp):
    
        # if a change has been made, write anew, else write original....
        if self.modified:
            fp.write("def ScriptProperties():\n    return {")
            fp.write("\n        'Author': ")
            fp.write(self.auth)
            fp.write(",\n        'Copyright': ")
            fp.write(self.copy)
            fp.write(",\n        'Description': ")
            fp.write(self.desc)
            fp.write(",\n        'Host': ")
            fp.write(self.host)
            fp.write(",\n        'Host Version': ")
            fp.write(self.hostver, "\n        }\n")
        else:
            fp.write(self.block)            

#############################################
class PyPSPCmd(PyBlock):
    def __init__(self, cmd, block, cmdname, parameters):
        # initialize the base class first
        PyBlock.__init__ (self, cmd, block)

        self.cmdname = cmdname
        self.edited = 0
        self.parms = parameters         # csl.  may not need....
        if cmd == "PSPCmd":
            self.commented = 0              # command is hot and not commented out
        else:
            self.commented = 1
        self.initialCommented = self.commented
            
        # call app to determine if the command is editable...  csl...
        self.isEditable = 1
        
        # set the execution mode
        if block.find('App.Constants.ExecutionMode.Default'):
            self.exmode = "default"
        elif block.find('App.Constants.ExecutionMode.Silent'):
            self.exmode = "silent"
        elif block.find('App.Constants.ExecutionMode.Verbose'):   # csl swagged label..
            self.exmode = "verbose"
        else:
            self.exmode = "defaultNotCoded"
        self.initialExMode = self.exmode

    def write(self, fp):
    
        # if a change has been made, write anew, else write original....
        if self.modified:
            
            # if execution mode has been changed then modify it...  ok, whack it in...
            if self.initialExMode <> self.exmode:
                if self.initialExMode == "silent":
                    # change from silent to something new
                    if self.exmode == "verbose":
                        block.replace("'App.Constants.ExecutionMode.Silent'",
                                      "'App.Constants.ExecutionMode.Verbose'", 1)
                    else:
                        block.replace("'App.Constants.ExecutionMode.Silent'",
                                      "'App.Constants.ExecutionMode.Defau1t'", 1)
                    
                elif self.initialExMode == "verbose":
                    # change from verbose to something new
                    if self.exmode == "silent":
                        block.replace("'App.Constants.ExecutionMode.Verbose'",
                                      "'App.Constants.ExecutionMode.Silent'", 1)
                    else:
                        block.replace("'App.Constants.ExecutionMode.Verbose'",
                                      "'App.Constants.ExecutionMode.Defau1t'", 1)
                    
                elif self.initialExMode == "default":
                    # change from verbose to something new
                    if self.exmode == "silent":
                        block.replace("'App.Constants.ExecutionMode.Default'",
                                      "'App.Constants.ExecutionMode.Silent'", 1)
                    else:
                        block.replace("'App.Constants.ExecutionMode.Default'",
                                      "'App.Constants.ExecutionMode.Verbose'", 1)
  
                else:
                    # initial state was default not coded.  insert into general settings.

                    if self.exmode == "verbose":
                        exModeToInsert = "            'App.Constants.ExecutionMode.Verbose'"
                    else:
                        exModeToInsert = "            'App.Constants.ExecutionMode.Silent'"
                         
                    if block.find("'GeneralSettings': {"):
                        block.replace("'GeneralSettings': {",
                                      "'GeneralSettings': {\n" + exModeToInsert, 1)
                    else:
                        # no general settings found.  insert after open brace
                        if block.find("{"):
                            block.replace("{",
                                      "'{\n            'GeneralSettings': {\n" + exModeToInsert + "},", 1)
 

            # if commented state has been changed from initial, change it...
            if self.initialCommented <> self.commented:
                if self.initialCommented:
                    # was initially commented and now is not.  put a space in char pos 1
                    # for all lines in the command
                    i = 0
                    newline = 1
                    while i < len(block):
                        if newline and block[i] == '#':
                            block [i] = ' '
                        else:
                            newline = 0
                            if block[i] == '\n':
                                newline = 1
                        i = i + 1
                else:
                    # was initially not commented and now it should be.  put a # in char pos
                    # 1 for all lines in the command
                    i = 0
                    newline = 1
                    while i < len(block):
                        if newline and block[i] == ' ':
                            block [i] = '#'
                        else:
                            newline = 0
                            if block[i] == '\n':
                                newline = 1
                        i = i + 1
                        
#            if self.edited:
                # call the application to reform the parms.  or was this done at edit time
                # csl ??????
            
        else:
            fp.write(self.block)            
