from Sketch import load, SketchLoadError

def insert_file(context, filename):
    # most of this is copied from Sketch/UI/mainwindow.py
    app = context.application
    try:
        doc = load.load_drawing(filename)
        group = doc.as_group()
    except SketchLoadError, value:
        app.MessageBox(title = "Insert Document",
                       message = "An error occurred:\n" + str(value))
    else:
        messages = doc.meta.load_messages
        if messages:
            app.MessageBox(title = "Insert Document",
                           message = "Warnings from the import filter:\n"
                                   + messages)
    #
    if group is not None:
        if group.NumObjects() == 1:
            # The document contained exactly one normal layer
            group = group.Ungroup()[0]   # Ungroup return a list of children
            if group.is_Group and group.NumObjects() == 1:
                # The layer had exactly one child
                # is_Group should always be true...
                group = group.Ungroup()[0]
        context.main_window.canvas.PlaceObject(group)
    else:
        app.MessageBox(title = "Insert Document",
                       message = "The document is empty")

# register scripts
import Sketch.Scripting
Sketch.Scripting.AddFunction('insert_gnd', 'GND', insert_file,
                             args = ("/some/where/gnd.sk",),
                             menu = 'Insert',
                             script_type = Sketch.Scripting.AdvancedScript)

