import rhinoscriptsyntax as rs
import Rhino
import scriptcontext as sc
from System import Guid


def UnlockSelectedLayers():
    
    allIds = rs.AllObjects()
    lockedIds = []
    unlockedIds = []
    blnLocked=False
    blnUnlocked = False
    
    for id in allIds:
        if rs.IsObjectLocked(id):
            if not rs.IsObjectHidden(id):
                lockedIds.append(id)
                blnUnlocked = True
        else:
            if not rs.LayerLocked(rs.ObjectLayer(id)):
                unlockedIds.append(id)
                blnLocked = True
    
    
    if blnUnlocked: rs.LockObjects(unlockedIds)
    if blnLocked: rs.UnlockObjects(lockedIds)

    layerIds  = rs.LayerIds()
    blnLockedLayers = False
    locked = []
    for id in layerIds:
        if rs.LayerLocked(id):
            blnLockedLayers = True
            locked.append(id)
            rs.LayerLocked(id, False)

    if not blnLocked and not blnLockedLayers:
        if blnUnlocked: rs.UnlockObjects(unlocledIds)
        print "No locked objects or layers found"
        return

    ids = rs.GetObjects()
    
    
    if not ids:
        for id in locked:
            rs.LayerLocked(id, True)
            rs.LockObjects(lockedIds)
            rs.UnlockObjects(unlockedIds)
        return
    
    def GetLayerParents(id):
        lIdx = sc.doc.Layers.Find(id, True)
        layer = sc.doc.Layers[lIdx].FullPath
        parents = []
        while True:
            idx = layer.rfind("::")
            if idx != -1:
                layer = layer[:idx]
                parents.append(Guid(rs.LayerId(layer)))
            else:
                return parents

    for id in ids:
        name = rs.ObjectLayer(id)
        lId = Guid(rs.LayerId(name))
        
        if lId in locked:
            
            locked.pop(locked.index(lId))
            pars = GetLayerParents(lId)
            if pars:
                for parId in pars:
                    if parId in locked:
                        locked.pop(locked.index(parId))

        if id in lockedIds:
            lockedIds.pop(lockedIds.index(id))
            
    for id in locked:
        rs.LayerLocked(id, True)
        
    rs.LockObjects(lockedIds)
    rs.UnlockObjects(unlockedIds)
        
        
    for id in ids: rs.SelectObject(id)

    
if __name__ == "__main__": UnlockSelectedLayers()