import win32gui, win32com.client
import re
import threading
import pythoncom

class WindowManager(object):
    """Encapsulates some calls to the winapi for window management"""
    def __init__ (self):
        """Constructor"""
        self._handle = None

    def find_window(self, class_name, window_name = None):
        """find a window by its class_name"""
        self._handle = win32gui.FindWindow(class_name, window_name)

    def _window_enum_callback(self, hwnd, regex):
        '''Pass to win32gui.EnumWindows() to check all the opened windows'''
        if re.match(regex, str(win32gui.GetWindowText(hwnd))) != None:
            self._handle = hwnd

    def find_window_regex(self, regex):
        self._handle = None
        win32gui.EnumWindows(self._window_enum_callback, regex)

    def set_foreground(self):
        """put the window in the foreground"""

        try:
            # "this is not the main thread" problem (CoInitialize has not been called)
            if threading.currentThread().getName() <> 'MainThread':
                pythoncom.CoInitialize()

            # "this is not the active window" problem (pywintypes.error: (0, 'SetForegroundWindow', 'No error message is available'))
            shell = win32com.client.Dispatch("WScript.Shell")
            shell.SendKeys('^')

            win32gui.SetForegroundWindow(self._handle)
        except Exception as e:
            print e
