import sys
import win32gui, win32con, win32api
import re, traceback
from time import sleep

class cWindow:
    def __init__(self):
        self._hwnd = None

    def ChangeTopness(self, ontop=True):
        print "style = {:x}".format (win32gui.GetWindowLong(self._hwnd, win32con.GWL_EXSTYLE))
        win32gui.SetWindowPos(self._hwnd, win32con.HWND_TOPMOST if ontop else win32con.HWND_NOTOPMOST, 0, 0, 0, 0, 0x0013)
        print "new style = {:x}".format (win32gui.GetWindowLong(self._hwnd, win32con.GWL_EXSTYLE))

    def _window_enum_callback(self, hwnd, regex):
        wintext = str(win32gui.GetWindowText(hwnd))
        if self._hwnd is None and re.match(regex, wintext) is not None and wintext.find (sys.argv[0]) < 0:
            self._hwnd = hwnd
            print "Found {}".format (win32gui.GetWindowText (hwnd))
            return False
        return True

    def find_window_regex(self, regex):
        self._hwnd = None
        try:
          win32gui.EnumWindows(self._window_enum_callback, regex)
        except:
          if win32api.GetLastError() != 0:
            raise

def main():
    if len (sys.argv) != 3:
      print "Usage: ontoper.py <window title regex> <top|notop>"
      sys.exit (1)
    regex = sys.argv[1]
    cW = cWindow()
    cW.find_window_regex(regex)
    cW.ChangeTopness(sys.argv[2] == "top")

main()
