import comtypes
import comtypes.server.localserver
import comtypes.server.register

import os

from comtypes.client import GetModule
# generate wrapper code for the type library, this needs
# to be done only once (but also each time the IDL file changes)
GetModule("sample.tlb")

from comtypes.gen.MyTypeLib import MyObject

class MyObjectImpl(MyObject):
    # registry entries
    _reg_threading_ = "Both"
    _reg_progid_ = "MyTypeLib.MyObject.1"
    _reg_novers_progid_ = "MyTypeLib.MyObject"
    _reg_desc_ = "Simple COM server for testing"
    _reg_clsctx_ = comtypes.CLSCTX_LOCAL_SERVER
    _regcls_ = comtypes.server.localserver.REGCLS_MULTIPLEUSE

    def MyMethod(self, print_this):
        print("Hello World! You called the MyObject method MyMethod! You asked to print "
              "\n          %s" % print_this)
        return "It worked!"

if __name__ == "__main__":
    import comtypes.server
    import sys

    if len(sys.argv) > 1:
        arg = sys.argv[1]
        if arg == '/runloop':
            try:
                print("Entering server run loop! Waiting for client call.")
                while True:
                    comtypes.server.localserver.run([MyObjectImpl])
                    print("Re-entering server run loop! Waiting for client call.")
            except (KeyboardInterrupt, SystemExit) as e:
                print("!! Caught exception! \n%r" % e)
        elif arg == '/regserver':
            comtypes.server.register.UseCommandLine(MyObjectImpl)
        else:
            print("ERROR: Unrecognized argument %r" % arg)
    else:
        print("ERROR: Needs at least one argument [/regserver|/runloop]")
