""" Dieses Python Skript ist nur für Demonstrationszwecke gedacht. Fuer die Nutzung in Archicad muss jedes Skript immer an das jeweilige Projekt angepasst werden. """

from archicad import ACConnection

conn = ACConnection.connect()
assert conn

acc = conn.commands
act = conn.types
acu = conn.utilities


def isLinkNavigatorItem(item : act.NavigatorItem):
    return item.sourceNavigatorItemId is not None


layoutBookTree = acc.GetNavigatorItemTree(act.NavigatorTreeId('LayoutBook'))
links = acu.FindInNavigatorItemTree(layoutBookTree.rootItem, isLinkNavigatorItem)

for publisherSetName in acc.GetPublisherSetNames():
	publisherSetTree = acc.GetNavigatorItemTree(act.NavigatorTreeId('PublisherSets', publisherSetName))
	links += acu.FindInNavigatorItemTree(publisherSetTree.rootItem, isLinkNavigatorItem)

sourcesOfLinks = set(link.sourceNavigatorItemId.guid for link in links)

viewMapTree = acc.GetNavigatorItemTree(act.NavigatorTreeId('ViewMap'))
unusedViewTreeItems = acu.FindInNavigatorItemTree(viewMapTree.rootItem, lambda node: not acu.FindInNavigatorItemTree(node, lambda i: i.navigatorItemId.guid in sourcesOfLinks))
unusedViewTreeItemsFiltered = []
for ii in unusedViewTreeItems:
    isChildOfUnused = False
    for jj in unusedViewTreeItems:
        if ii != jj and acu.FindInNavigatorItemTree(jj, lambda node: node.navigatorItemId.guid == ii.navigatorItemId.guid):
            isChildOfUnused = True
            break
    if not isChildOfUnused:
        unusedViewTreeItemsFiltered.append(ii)
unusedViewTreeItems = unusedViewTreeItemsFiltered

folderName = '-- Unbenutzte Ausschnitte --'
existingUnusedViewsFolders = acu.FindInNavigatorItemTree(viewMapTree.rootItem, lambda i: i.name == folderName)
unusedViewsFolder = acc.CreateViewMapFolder(act.FolderParameters(folderName)) if not existingUnusedViewsFolders else existingUnusedViewsFolders[0].navigatorItemId

for item in unusedViewTreeItems:
    try:
        acc.MoveNavigatorItem(item.navigatorItemId, unusedViewsFolder)
    except:
        continue
